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.
Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≤ a ≤ b ≤ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set:
<image>
Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph.
When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots.
How many dominoes at most can Anadi place on the edges of his graph?
Input
The first line contains two integers n and m (1 ≤ n ≤ 7, 0 ≤ m ≤ (n⋅(n-1))/(2)) — the number of vertices and the number of edges in the graph.
The next m lines contain two integers each. Integers in the i-th line are a_i and b_i (1 ≤ a, b ≤ n, a ≠ b) and denote that there is an edge which connects vertices a_i and b_i.
The graph might be disconnected. It's however guaranteed that the graph doesn't contain any self-loops, and that there is at most one edge between any pair of vertices.
Output
Output one integer which denotes the maximum number of dominoes which Anadi can place on the edges of the graph.
Examples
Input
4 4
1 2
2 3
3 4
4 1
Output
4
Input
7 0
Output
0
Input
3 1
1 3
Output
1
Input
7 21
1 2
1 3
1 4
1 5
1 6
1 7
2 3
2 4
2 5
2 6
2 7
3 4
3 5
3 6
3 7
4 5
4 6
4 7
5 6
5 7
6 7
Output
16
Note
Here is an illustration of Anadi's graph from the first sample test:
<image>
And here is one of the ways to place a domino on each of its edges:
<image>
Note that each vertex is faced by the halves of dominoes with the same number of dots. For instance, all halves directed toward vertex 1 have three dots.
Submitted Solution:
```
n, m = [int(x) for x in input().split()]
if n <= 6:
for i in range(m):
input()
print(m)
exit()
graph = [set() for _ in range(7)]
for i in range(m):
edge = [int(x) - 1 for x in input().split()]
u = edge[0]
v = edge[1]
graph[u].add(v)
graph[v].add(u)
answer = 0
for i, u in enumerate(graph):
for j, v in enumerate(graph):
if i == j:
continue
intersectionLength = len(u.intersection(v))
answer = max(answer, m - intersectionLength)
print(answer)
``` | instruction | 0 | 73,416 | 13 | 146,832 |
Yes | output | 1 | 73,416 | 13 | 146,833 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≤ a ≤ b ≤ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set:
<image>
Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph.
When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots.
How many dominoes at most can Anadi place on the edges of his graph?
Input
The first line contains two integers n and m (1 ≤ n ≤ 7, 0 ≤ m ≤ (n⋅(n-1))/(2)) — the number of vertices and the number of edges in the graph.
The next m lines contain two integers each. Integers in the i-th line are a_i and b_i (1 ≤ a, b ≤ n, a ≠ b) and denote that there is an edge which connects vertices a_i and b_i.
The graph might be disconnected. It's however guaranteed that the graph doesn't contain any self-loops, and that there is at most one edge between any pair of vertices.
Output
Output one integer which denotes the maximum number of dominoes which Anadi can place on the edges of the graph.
Examples
Input
4 4
1 2
2 3
3 4
4 1
Output
4
Input
7 0
Output
0
Input
3 1
1 3
Output
1
Input
7 21
1 2
1 3
1 4
1 5
1 6
1 7
2 3
2 4
2 5
2 6
2 7
3 4
3 5
3 6
3 7
4 5
4 6
4 7
5 6
5 7
6 7
Output
16
Note
Here is an illustration of Anadi's graph from the first sample test:
<image>
And here is one of the ways to place a domino on each of its edges:
<image>
Note that each vertex is faced by the halves of dominoes with the same number of dots. For instance, all halves directed toward vertex 1 have three dots.
Submitted Solution:
```
n, m = [int(i) for i in input().split()]
data = []
for i in range(m):
data.append([int(j) - 1 for j in input().split()])
ans = 0
for i in range(6 ** n):
k = i
num = [0] * n
for j in range(n):
dig = k % 6
k //= 6
num[j] = dig
st = set()
for e in data:
t = [num[e[0]],num[e[1]]]
if t[0] > t[1]:
t.reverse()
st.add(tuple(t))
ans = max(len(st), ans)
print(ans)
``` | instruction | 0 | 73,417 | 13 | 146,834 |
Yes | output | 1 | 73,417 | 13 | 146,835 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≤ a ≤ b ≤ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set:
<image>
Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph.
When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots.
How many dominoes at most can Anadi place on the edges of his graph?
Input
The first line contains two integers n and m (1 ≤ n ≤ 7, 0 ≤ m ≤ (n⋅(n-1))/(2)) — the number of vertices and the number of edges in the graph.
The next m lines contain two integers each. Integers in the i-th line are a_i and b_i (1 ≤ a, b ≤ n, a ≠ b) and denote that there is an edge which connects vertices a_i and b_i.
The graph might be disconnected. It's however guaranteed that the graph doesn't contain any self-loops, and that there is at most one edge between any pair of vertices.
Output
Output one integer which denotes the maximum number of dominoes which Anadi can place on the edges of the graph.
Examples
Input
4 4
1 2
2 3
3 4
4 1
Output
4
Input
7 0
Output
0
Input
3 1
1 3
Output
1
Input
7 21
1 2
1 3
1 4
1 5
1 6
1 7
2 3
2 4
2 5
2 6
2 7
3 4
3 5
3 6
3 7
4 5
4 6
4 7
5 6
5 7
6 7
Output
16
Note
Here is an illustration of Anadi's graph from the first sample test:
<image>
And here is one of the ways to place a domino on each of its edges:
<image>
Note that each vertex is faced by the halves of dominoes with the same number of dots. For instance, all halves directed toward vertex 1 have three dots.
Submitted Solution:
```
from collections import Counter
def main():
n, m = map(int, input().split())
edges = [tuple(map(int, input().split())) for _ in range(m)]
cnt = Counter()
for x, y in edges:
cnt[x] += 1
cnt[y] += 1
mf = set(x for x, y in cnt.most_common(6))
ans = 0
for x, y in edges:
if x in mf and y in mf:
ans += 1
if len(cnt) == 7:
ans += 1
print(ans)
if __name__ == "__main__":
main()
``` | instruction | 0 | 73,418 | 13 | 146,836 |
No | output | 1 | 73,418 | 13 | 146,837 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≤ a ≤ b ≤ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set:
<image>
Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph.
When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots.
How many dominoes at most can Anadi place on the edges of his graph?
Input
The first line contains two integers n and m (1 ≤ n ≤ 7, 0 ≤ m ≤ (n⋅(n-1))/(2)) — the number of vertices and the number of edges in the graph.
The next m lines contain two integers each. Integers in the i-th line are a_i and b_i (1 ≤ a, b ≤ n, a ≠ b) and denote that there is an edge which connects vertices a_i and b_i.
The graph might be disconnected. It's however guaranteed that the graph doesn't contain any self-loops, and that there is at most one edge between any pair of vertices.
Output
Output one integer which denotes the maximum number of dominoes which Anadi can place on the edges of the graph.
Examples
Input
4 4
1 2
2 3
3 4
4 1
Output
4
Input
7 0
Output
0
Input
3 1
1 3
Output
1
Input
7 21
1 2
1 3
1 4
1 5
1 6
1 7
2 3
2 4
2 5
2 6
2 7
3 4
3 5
3 6
3 7
4 5
4 6
4 7
5 6
5 7
6 7
Output
16
Note
Here is an illustration of Anadi's graph from the first sample test:
<image>
And here is one of the ways to place a domino on each of its edges:
<image>
Note that each vertex is faced by the halves of dominoes with the same number of dots. For instance, all halves directed toward vertex 1 have three dots.
Submitted Solution:
```
n,m = map(int,input().split(" "))
a = 0
b = 0
arr = [0]*7
for i in range(m):
a,b = map(int,input().split(" "))
arr[a-1]+=1
arr[b-1]+=1
if(n<=6):
print(m)
else:
mini = min(arr)
if(mini==0):
print(m)
else:
print(m+1-mini)
``` | instruction | 0 | 73,419 | 13 | 146,838 |
No | output | 1 | 73,419 | 13 | 146,839 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≤ a ≤ b ≤ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set:
<image>
Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph.
When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots.
How many dominoes at most can Anadi place on the edges of his graph?
Input
The first line contains two integers n and m (1 ≤ n ≤ 7, 0 ≤ m ≤ (n⋅(n-1))/(2)) — the number of vertices and the number of edges in the graph.
The next m lines contain two integers each. Integers in the i-th line are a_i and b_i (1 ≤ a, b ≤ n, a ≠ b) and denote that there is an edge which connects vertices a_i and b_i.
The graph might be disconnected. It's however guaranteed that the graph doesn't contain any self-loops, and that there is at most one edge between any pair of vertices.
Output
Output one integer which denotes the maximum number of dominoes which Anadi can place on the edges of the graph.
Examples
Input
4 4
1 2
2 3
3 4
4 1
Output
4
Input
7 0
Output
0
Input
3 1
1 3
Output
1
Input
7 21
1 2
1 3
1 4
1 5
1 6
1 7
2 3
2 4
2 5
2 6
2 7
3 4
3 5
3 6
3 7
4 5
4 6
4 7
5 6
5 7
6 7
Output
16
Note
Here is an illustration of Anadi's graph from the first sample test:
<image>
And here is one of the ways to place a domino on each of its edges:
<image>
Note that each vertex is faced by the halves of dominoes with the same number of dots. For instance, all halves directed toward vertex 1 have three dots.
Submitted Solution:
```
n, m = map(int, input().split())
d = [0 for i in range(7)]
g = [[] for i in range(7)]
for i in range(m):
x, y = map(int, input().split())
x -= 1
y -= 1
d[x] += 1
d[y] += 1
g[x].append(y)
g[y].append(x)
mn = min(d)
for i in range(7):
for j in range(i):
good = True
for k in range(7):
if((k in g[i]) and (k in g[j])):
good = False
if(good):
mn = 0
m -= mn
if(mn > 0):
m += 1
print(m)
``` | instruction | 0 | 73,420 | 13 | 146,840 |
No | output | 1 | 73,420 | 13 | 146,841 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≤ a ≤ b ≤ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set:
<image>
Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph.
When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots.
How many dominoes at most can Anadi place on the edges of his graph?
Input
The first line contains two integers n and m (1 ≤ n ≤ 7, 0 ≤ m ≤ (n⋅(n-1))/(2)) — the number of vertices and the number of edges in the graph.
The next m lines contain two integers each. Integers in the i-th line are a_i and b_i (1 ≤ a, b ≤ n, a ≠ b) and denote that there is an edge which connects vertices a_i and b_i.
The graph might be disconnected. It's however guaranteed that the graph doesn't contain any self-loops, and that there is at most one edge between any pair of vertices.
Output
Output one integer which denotes the maximum number of dominoes which Anadi can place on the edges of the graph.
Examples
Input
4 4
1 2
2 3
3 4
4 1
Output
4
Input
7 0
Output
0
Input
3 1
1 3
Output
1
Input
7 21
1 2
1 3
1 4
1 5
1 6
1 7
2 3
2 4
2 5
2 6
2 7
3 4
3 5
3 6
3 7
4 5
4 6
4 7
5 6
5 7
6 7
Output
16
Note
Here is an illustration of Anadi's graph from the first sample test:
<image>
And here is one of the ways to place a domino on each of its edges:
<image>
Note that each vertex is faced by the halves of dominoes with the same number of dots. For instance, all halves directed toward vertex 1 have three dots.
Submitted Solution:
```
from collections import defaultdict
MyDict = defaultdict(int)
X = list(map(int, input().split()))
Edges = []
for i in range(X[1]):
Temp = list(map(int, input().split()))
Edges.append(Temp)
MyDict[Temp[0]] += 1
MyDict[Temp[1]] += 1
if len(MyDict.keys()) < 7:
print(X[1])
exit()
MIN = min(MyDict.values())
Which = 0
for key in MyDict.keys():
if MyDict[key] == MIN:
Which = key
break
Count = 0
Picked = 0
for i in range(X[1]):
if Which in Edges[i]:
Count += 1
else:
Picked += 1
if Count == 1:
print(X[1])
else:
print(X[1] - Count + 1 if Picked == 15 else X[1] - Count + 2)
``` | instruction | 0 | 73,421 | 13 | 146,842 |
No | output | 1 | 73,421 | 13 | 146,843 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached 100 million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?
You're given a tree — a connected undirected graph consisting of n vertices connected by n - 1 edges. The tree is rooted at vertex 1. A vertex u is called an ancestor of v if it lies on the shortest path between the root and v. In particular, a vertex is an ancestor of itself.
Each vertex v is assigned its beauty x_v — a non-negative integer not larger than 10^{12}. This allows us to define the beauty of a path. Let u be an ancestor of v. Then we define the beauty f(u, v) as the greatest common divisor of the beauties of all vertices on the shortest path between u and v. Formally, if u=t_1, t_2, t_3, ..., t_k=v are the vertices on the shortest path between u and v, then f(u, v) = \gcd(x_{t_1}, x_{t_2}, ..., x_{t_k}). Here, \gcd denotes the greatest common divisor of a set of numbers. In particular, f(u, u) = \gcd(x_u) = x_u.
Your task is to find the sum
$$$ ∑_{u is an ancestor of v} f(u, v). $$$
As the result might be too large, please output it modulo 10^9 + 7.
Note that for each y, \gcd(0, y) = \gcd(y, 0) = y. In particular, \gcd(0, 0) = 0.
Input
The first line contains a single integer n (2 ≤ n ≤ 100 000) — the number of vertices in the tree.
The following line contains n integers x_1, x_2, ..., x_n (0 ≤ x_i ≤ 10^{12}). The value x_v denotes the beauty of vertex v.
The following n - 1 lines describe the edges of the tree. Each of them contains two integers a, b (1 ≤ a, b ≤ n, a ≠ b) — the vertices connected by a single edge.
Output
Output the sum of the beauties on all paths (u, v) such that u is ancestor of v. This sum should be printed modulo 10^9 + 7.
Examples
Input
5
4 5 6 0 8
1 2
1 3
1 4
4 5
Output
42
Input
7
0 2 3 0 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
30
Note
The following figure shows all 10 possible paths for which one endpoint is an ancestor of another endpoint. The sum of beauties of all these paths is equal to 42:
<image> | instruction | 0 | 73,422 | 13 | 146,844 |
Tags: math, number theory, trees
Correct Solution:
```
from math import gcd
from collections import deque
from bisect import bisect_left
from sys import setrecursionlimit
MOD = 1000000007
def modInt(mod):
class ModInt:
def __init__(self, value):
self.value = value % mod
def __int__(self):
return self.value
def __eq__(self, other):
return self.value == other.value
def __hash__(self):
return hash(self.value)
def __add__(self, other):
return ModInt(self.value + int(other))
def __sub__(self, other):
return ModInt(self.value - int(other))
def __mul__(self, other):
return ModInt(self.value * int(other))
def __floordiv__(self, other):
return ModInt(self.value // int(other))
def __truediv__(self, other):
return ModInt(self.value * pow(int(other), mod - 2, mod))
return ModInt
ModInt = modInt(MOD)
def main():
n = int(input())
setrecursionlimit(n+100)
xx = [0] + [int(x) for x in input().split()]
edges = []
neighbors = [[] for _ in range(n+1)]
for _ in range(n-1):
v1, v2 = [int(x) for x in input().split()]
neighbors[v1].append(v2)
neighbors[v2].append(v1)
visited = [False] * (n+1)
dq = deque()
dq.append((1,[]))
sum = ModInt(0)
while dq:
u,gcds = dq.popleft()
gcdns = [[xx[u], 1]]
sum = (sum + xx[u])
for g, c in gcds:
gcdn = gcd(xx[u], g)
sum = (sum + gcdn*c)
if gcdn == gcdns[-1][0]:
gcdns[-1][1] += c
else:
gcdns.append([gcdn, c])
visited[u] = True
for v in neighbors[u]:
if not visited[v]:
dq.append((v, gcdns))
print(int(sum))
if __name__ == "__main__":
main()
``` | output | 1 | 73,422 | 13 | 146,845 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached 100 million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?
You're given a tree — a connected undirected graph consisting of n vertices connected by n - 1 edges. The tree is rooted at vertex 1. A vertex u is called an ancestor of v if it lies on the shortest path between the root and v. In particular, a vertex is an ancestor of itself.
Each vertex v is assigned its beauty x_v — a non-negative integer not larger than 10^{12}. This allows us to define the beauty of a path. Let u be an ancestor of v. Then we define the beauty f(u, v) as the greatest common divisor of the beauties of all vertices on the shortest path between u and v. Formally, if u=t_1, t_2, t_3, ..., t_k=v are the vertices on the shortest path between u and v, then f(u, v) = \gcd(x_{t_1}, x_{t_2}, ..., x_{t_k}). Here, \gcd denotes the greatest common divisor of a set of numbers. In particular, f(u, u) = \gcd(x_u) = x_u.
Your task is to find the sum
$$$ ∑_{u is an ancestor of v} f(u, v). $$$
As the result might be too large, please output it modulo 10^9 + 7.
Note that for each y, \gcd(0, y) = \gcd(y, 0) = y. In particular, \gcd(0, 0) = 0.
Input
The first line contains a single integer n (2 ≤ n ≤ 100 000) — the number of vertices in the tree.
The following line contains n integers x_1, x_2, ..., x_n (0 ≤ x_i ≤ 10^{12}). The value x_v denotes the beauty of vertex v.
The following n - 1 lines describe the edges of the tree. Each of them contains two integers a, b (1 ≤ a, b ≤ n, a ≠ b) — the vertices connected by a single edge.
Output
Output the sum of the beauties on all paths (u, v) such that u is ancestor of v. This sum should be printed modulo 10^9 + 7.
Examples
Input
5
4 5 6 0 8
1 2
1 3
1 4
4 5
Output
42
Input
7
0 2 3 0 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
30
Note
The following figure shows all 10 possible paths for which one endpoint is an ancestor of another endpoint. The sum of beauties of all these paths is equal to 42:
<image> | instruction | 0 | 73,423 | 13 | 146,846 |
Tags: math, number theory, trees
Correct Solution:
```
from math import gcd
from collections import deque
from bisect import bisect_left
from sys import setrecursionlimit
MOD = 1000000007
def main():
n = int(input())
setrecursionlimit(n+100)
xx = [0] + [int(x) for x in input().split()]
edges = []
for _ in range(n-1):
edge = [int(x) for x in input().split()]
edges.append(edge)
edges.append(list(reversed(edge)))
edges.sort()
visited = [False] * (n+1)
dq = deque()
dq.append((1,[]))
sum = 0
while dq:
u,gcds = dq.popleft()
gcdns = [[xx[u], 1]]
sum = (sum + xx[u]) % MOD
for g, c in gcds:
gcdn = gcd(xx[u], g)
sum = (sum + gcdn*c) % MOD
if gcdn == gcdns[-1][0]:
gcdns[-1][1] += c
else:
gcdns.append([gcdn, c])
visited[u] = True
i = bisect_left(edges, [u, 0])
if i == 2*(n-1):
continue
w, v = edges[i]
while w == u and i < 2*(n-1):
if not visited[v]:
dq.append((v, gcdns))
i+=1
if i < 2*(n-1):
w, v = edges[i]
print(sum)
if __name__ == "__main__":
main()
``` | output | 1 | 73,423 | 13 | 146,847 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached 100 million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?
You're given a tree — a connected undirected graph consisting of n vertices connected by n - 1 edges. The tree is rooted at vertex 1. A vertex u is called an ancestor of v if it lies on the shortest path between the root and v. In particular, a vertex is an ancestor of itself.
Each vertex v is assigned its beauty x_v — a non-negative integer not larger than 10^{12}. This allows us to define the beauty of a path. Let u be an ancestor of v. Then we define the beauty f(u, v) as the greatest common divisor of the beauties of all vertices on the shortest path between u and v. Formally, if u=t_1, t_2, t_3, ..., t_k=v are the vertices on the shortest path between u and v, then f(u, v) = \gcd(x_{t_1}, x_{t_2}, ..., x_{t_k}). Here, \gcd denotes the greatest common divisor of a set of numbers. In particular, f(u, u) = \gcd(x_u) = x_u.
Your task is to find the sum
$$$ ∑_{u is an ancestor of v} f(u, v). $$$
As the result might be too large, please output it modulo 10^9 + 7.
Note that for each y, \gcd(0, y) = \gcd(y, 0) = y. In particular, \gcd(0, 0) = 0.
Input
The first line contains a single integer n (2 ≤ n ≤ 100 000) — the number of vertices in the tree.
The following line contains n integers x_1, x_2, ..., x_n (0 ≤ x_i ≤ 10^{12}). The value x_v denotes the beauty of vertex v.
The following n - 1 lines describe the edges of the tree. Each of them contains two integers a, b (1 ≤ a, b ≤ n, a ≠ b) — the vertices connected by a single edge.
Output
Output the sum of the beauties on all paths (u, v) such that u is ancestor of v. This sum should be printed modulo 10^9 + 7.
Examples
Input
5
4 5 6 0 8
1 2
1 3
1 4
4 5
Output
42
Input
7
0 2 3 0 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
30
Note
The following figure shows all 10 possible paths for which one endpoint is an ancestor of another endpoint. The sum of beauties of all these paths is equal to 42:
<image> | instruction | 0 | 73,424 | 13 | 146,848 |
Tags: math, number theory, trees
Correct Solution:
```
from math import gcd
from collections import deque
from bisect import bisect_left
from sys import setrecursionlimit
MOD = 1000000007
def main():
n = int(input())
setrecursionlimit(n+100)
xx = [0] + [int(x) for x in input().split()]
edges = []
neighbors = [[] for _ in range(n+1)]
for _ in range(n-1):
v1, v2 = [int(x) for x in input().split()]
neighbors[v1].append(v2)
neighbors[v2].append(v1)
visited = [False] * (n+1)
dq = deque()
dq.append((1,[]))
sum = 0
while dq:
u,gcds = dq.popleft()
gcdns = [[xx[u], 1]]
sum = (sum + xx[u]) % MOD
for g, c in gcds:
gcdn = gcd(xx[u], g)
sum = (sum + gcdn*c) % MOD
if gcdn == gcdns[-1][0]:
gcdns[-1][1] += c
else:
gcdns.append([gcdn, c])
visited[u] = True
for v in neighbors[u]:
if not visited[v]:
dq.append((v, gcdns))
print(sum)
if __name__ == "__main__":
main()
``` | output | 1 | 73,424 | 13 | 146,849 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached 100 million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?
You're given a tree — a connected undirected graph consisting of n vertices connected by n - 1 edges. The tree is rooted at vertex 1. A vertex u is called an ancestor of v if it lies on the shortest path between the root and v. In particular, a vertex is an ancestor of itself.
Each vertex v is assigned its beauty x_v — a non-negative integer not larger than 10^{12}. This allows us to define the beauty of a path. Let u be an ancestor of v. Then we define the beauty f(u, v) as the greatest common divisor of the beauties of all vertices on the shortest path between u and v. Formally, if u=t_1, t_2, t_3, ..., t_k=v are the vertices on the shortest path between u and v, then f(u, v) = \gcd(x_{t_1}, x_{t_2}, ..., x_{t_k}). Here, \gcd denotes the greatest common divisor of a set of numbers. In particular, f(u, u) = \gcd(x_u) = x_u.
Your task is to find the sum
$$$ ∑_{u is an ancestor of v} f(u, v). $$$
As the result might be too large, please output it modulo 10^9 + 7.
Note that for each y, \gcd(0, y) = \gcd(y, 0) = y. In particular, \gcd(0, 0) = 0.
Input
The first line contains a single integer n (2 ≤ n ≤ 100 000) — the number of vertices in the tree.
The following line contains n integers x_1, x_2, ..., x_n (0 ≤ x_i ≤ 10^{12}). The value x_v denotes the beauty of vertex v.
The following n - 1 lines describe the edges of the tree. Each of them contains two integers a, b (1 ≤ a, b ≤ n, a ≠ b) — the vertices connected by a single edge.
Output
Output the sum of the beauties on all paths (u, v) such that u is ancestor of v. This sum should be printed modulo 10^9 + 7.
Examples
Input
5
4 5 6 0 8
1 2
1 3
1 4
4 5
Output
42
Input
7
0 2 3 0 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
30
Note
The following figure shows all 10 possible paths for which one endpoint is an ancestor of another endpoint. The sum of beauties of all these paths is equal to 42:
<image>
Submitted Solution:
```
from math import gcd
from collections import deque
from bisect import bisect_left
from sys import setrecursionlimit
MOD = 1000000007
def main():
n = int(input())
setrecursionlimit(n+100)
xx = [0] + [int(x) for x in input().split()]
edges = []
for _ in range(n-1):
edge = [int(x) for x in input().split()]
edges.append(edge)
edges.append(list(reversed(edge)))
edges.sort()
visited = [False] * (n+1)
children = [[] for _ in range(n+1)]
dq = deque()
dq.append(1)
while dq:
v = dq.popleft()
visited[v] = True
i = bisect_left(edges, [v, 0])
if i == 2*(n-1):
continue
w, x = edges[i]
while w == v and i < 2*(n-1):
if not visited[x]:
children[v].append(x)
dq.append(x)
i+=1
if i < 2*(n-1):
w, x = edges[i]
def gcdsum(i, gcds):
gcdns = [[xx[i], 1]]
sum = xx[i]
for g, c in gcds:
gcdn = gcd(xx[i], g) * c
sum = (sum + gcdn) % MOD
if gcdn == gcdns[-1][0]:
gcdns[-1][1] += c
else:
gcdns.append([gcdn, c])
for v in children[i]:
sum = (sum + gcdsum(v, gcdns)) % MOD
return sum
print(gcdsum(1, []))
if __name__ == "__main__":
main()
``` | instruction | 0 | 73,425 | 13 | 146,850 |
No | output | 1 | 73,425 | 13 | 146,851 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Finally, you have defeated Razor and now, you are the Most Wanted street racer. Sergeant Cross has sent the full police force after you in a deadly pursuit. Fortunately, you have found a hiding spot but you fear that Cross and his force will eventually find you. To increase your chances of survival, you want to tune and repaint your BMW M3 GTR.
The car can be imagined as a permuted n-dimensional hypercube. A simple n-dimensional hypercube is an undirected unweighted graph built recursively as follows:
* Take two simple (n-1)-dimensional hypercubes one having vertices numbered from 0 to 2^{n-1}-1 and the other having vertices numbered from 2^{n-1} to 2^{n}-1. A simple 0-dimensional Hypercube is just a single vertex.
* Add an edge between the vertices i and i+2^{n-1} for each 0≤ i < 2^{n-1}.
A permuted n-dimensional hypercube is formed by permuting the vertex numbers of a simple n-dimensional hypercube in any arbitrary manner.
Examples of a simple and permuted 3-dimensional hypercubes are given below:
<image>
Note that a permuted n-dimensional hypercube has the following properties:
* There are exactly 2^n vertices.
* There are exactly n⋅ 2^{n-1} edges.
* Each vertex is connected to exactly n other vertices.
* There are no self-loops or duplicate edges.
Let's denote the permutation used to generate the permuted n-dimensional hypercube, representing your car, from a simple n-dimensional hypercube by P. Before messing up the functionalities of the car, you want to find this permutation so that you can restore the car if anything goes wrong. But the job isn't done yet.
You have n different colours numbered from 0 to n-1. You want to colour the vertices of this permuted n-dimensional hypercube in such a way that for each and every vertex u satisfying 0≤ u < 2^n and for each and every colour c satisfying 0≤ c < n, there is at least one vertex v adjacent to u having a colour c. In other words, from each and every vertex, it must be possible to reach a vertex of any colour by just moving to an adjacent vertex.
Given the permuted n-dimensional hypercube, find any valid permutation P and colouring.
Input
The first line of input contains a single integer t (1≤ t≤ 4096) — the number of test cases.
For each test case, the first line contains a single integer n (1≤ n≤ 16).
Each of the next n⋅ 2^{n-1} lines contain two integers u and v (0≤ u, v < 2^n) denoting that there is an edge between the vertices numbered u and v.
It is guaranteed that the graph described in the input is a permuted n-dimensional hypercube.
Additionally, it is guaranteed that the sum of 2^n over all test cases does not exceed 2^{16}=65 536.
Output
For each test case, print two lines.
In the first line, output any permutation P of length 2^n that can be used to transform a simple n-dimensional hypercube to the permuted n-dimensional hypercube given in the input. Two permuted hypercubes are considered the same if they have the same set of edges. If there are multiple answers, output any of them.
In the second line, print the colouring. If there is no way to colour the vertices satisfying the conditions, output -1. Otherwise, output a single line containing 2^n space separated integers. The i-th integer must be the colour of the vertex numbered (i-1) in the permuted n-dimensional hypercube. If there are multiple answers, output any of them.
Example
Input
3
1
0 1
2
0 1
1 2
2 3
3 0
3
0 1
0 5
0 7
1 2
1 4
2 5
2 6
3 5
3 6
3 7
4 6
4 7
Output
0 1
0 0
0 1 3 2
0 0 1 1
5 3 0 7 2 6 1 4
-1
Note
The colouring and the permuted hypercube for the first test case is shown below:
<image>
The colouring and the permuted hypercube for the second test case is shown below:
<image>
The permuted hypercube for the third test case is given in the problem statement. However, it can be shown that there exists no way to colour that cube satifying all the conditions. Note that some other permutations like [0, 5, 7, 3, 1, 2, 4, 6] and [0, 1, 5, 2, 7, 4, 3, 6] will also give the same permuted hypercube. | instruction | 0 | 73,592 | 13 | 147,184 |
Tags: bitmasks, constructive algorithms, divide and conquer, graphs, greedy, math
Correct Solution:
```
from collections import deque
from sys import stdin
import sys
tt = int(stdin.readline())
for loop in range(tt):
n = int(stdin.readline())
lis = [ [] for i in range(2**n)]
for i in range(n*(2**(n-1))):
u,v = map(int,stdin.readline().split())
lis[u].append(v)
lis[v].append(u)
rp = [0] * (2**n)
d = [float("inf")] * (2**n)
d[0] = 0
q = deque()
for i in range(n):
nexv = lis[0][i]
rp[nexv] = 2**i
d[nexv] = 1
q.append(nexv)
while q:
v = q.popleft()
for nexv in lis[v]:
if d[nexv] == float("inf"):
d[nexv] = d[v] + 1
q.append(nexv)
if d[nexv] > d[v]:
rp[nexv] |= rp[v]
p = [None] * (2**n)
for i in range(2**n):
p[rp[i]] = i
print (*p)
if (2**n) % n == 0:
c = [None] * (2**n)
for i in range(2**n):
now = 0
for j in range(n):
if 2**j & i > 0:
now ^= j
c[p[i]] = now
print (*c)
else:
print (-1)
``` | output | 1 | 73,592 | 13 | 147,185 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability.
Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes.
Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible.
Input
The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes.
Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints.
Output
In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids.
If there are multiple answers, print any of them.
Examples
Input
3 2
Output
2
1 2
2 3
Input
5 3
Output
3
1 2
2 3
3 4
3 5
Note
In the first example the only network is shown on the left picture.
In the second example one of optimal networks is shown on the right picture.
Exit-nodes are highlighted.
<image> | instruction | 0 | 73,844 | 13 | 147,688 |
Tags: constructive algorithms, greedy, implementation, trees
Correct Solution:
```
n, k = map(int, input().split())
r = (n-1)//k
l = n - 1
x, y, = 1, 2
diam = 2*r
if (n-1)%k == 1:
diam += 1
elif (n-1)%k >= 2:
diam += 2
print(diam)
for i in range(k):
br = r
if i < (n-1)%k:
br += 1
x = 1
for j in range(br):
print(x, y)
x = y
y = y + 1
l -= 1
``` | output | 1 | 73,844 | 13 | 147,689 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability.
Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes.
Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible.
Input
The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes.
Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints.
Output
In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids.
If there are multiple answers, print any of them.
Examples
Input
3 2
Output
2
1 2
2 3
Input
5 3
Output
3
1 2
2 3
3 4
3 5
Note
In the first example the only network is shown on the left picture.
In the second example one of optimal networks is shown on the right picture.
Exit-nodes are highlighted.
<image> | instruction | 0 | 73,845 | 13 | 147,690 |
Tags: constructive algorithms, greedy, implementation, trees
Correct Solution:
```
n,k=list(map(int,input().strip().split(' ')))
import math
L=math.ceil((n-(k+1))/(k))
remain=(n-(k+1))%(k)
if (n-(k+1))%(k)==0:
remain+=k
#print(L,remain,'L,remain')
if remain%(k)==1:
print(2*(L)+1)
else:
print(2*(L+1))
if 1==1:
if n==2:
print(1,2)
else:
temp=0
end=k+1
for j in range(2,k+1+1):
print(1,j)
if temp<remain:
for p in range(0,L):
if p==0:
print(j,end+1)
end+=1
else:
print(end,end+1)
end+=1
temp+=1
else:
for p in range(0,L-1):
if p==0:
print(j,end+1)
end+=1
else:
print(end,end+1)
end+=1
``` | output | 1 | 73,845 | 13 | 147,691 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability.
Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes.
Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible.
Input
The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes.
Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints.
Output
In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids.
If there are multiple answers, print any of them.
Examples
Input
3 2
Output
2
1 2
2 3
Input
5 3
Output
3
1 2
2 3
3 4
3 5
Note
In the first example the only network is shown on the left picture.
In the second example one of optimal networks is shown on the right picture.
Exit-nodes are highlighted.
<image> | instruction | 0 | 73,846 | 13 | 147,692 |
Tags: constructive algorithms, greedy, implementation, trees
Correct Solution:
```
def pr(m):
for i in range(len(m)):
print(' '.join([str(x) for x in m[i]]))
n, k = map(int, input().split())
edge = [[1, v] if v < k+1 else [v-k, v] for v in range(2, n+1)]
def get_min_max_radius(n, k):
r = (n-1) % k
base = (n-1) // k
if r == 0:
return base * 2
if r == 1:
return base * 2 + 1
return base * 2 + 2
print(get_min_max_radius(n, k))
pr(edge)
``` | output | 1 | 73,846 | 13 | 147,693 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability.
Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes.
Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible.
Input
The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes.
Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints.
Output
In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids.
If there are multiple answers, print any of them.
Examples
Input
3 2
Output
2
1 2
2 3
Input
5 3
Output
3
1 2
2 3
3 4
3 5
Note
In the first example the only network is shown on the left picture.
In the second example one of optimal networks is shown on the right picture.
Exit-nodes are highlighted.
<image> | instruction | 0 | 73,847 | 13 | 147,694 |
Tags: constructive algorithms, greedy, implementation, trees
Correct Solution:
```
n, k = map(int, input().split())
q = ((n-2) % k) +1
t = (n-1) // k
if q == 1:
print(2*t+1)
elif q == k:
print(2*t)
else:
print(2*t+2)
# print(t, q)
for i in range(2, n+1):
print(max(1, i-k), i)
``` | output | 1 | 73,847 | 13 | 147,695 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability.
Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes.
Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible.
Input
The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes.
Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints.
Output
In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids.
If there are multiple answers, print any of them.
Examples
Input
3 2
Output
2
1 2
2 3
Input
5 3
Output
3
1 2
2 3
3 4
3 5
Note
In the first example the only network is shown on the left picture.
In the second example one of optimal networks is shown on the right picture.
Exit-nodes are highlighted.
<image> | instruction | 0 | 73,848 | 13 | 147,696 |
Tags: constructive algorithms, greedy, implementation, trees
Correct Solution:
```
n, k = map(int, input().split())
x = (n - 1) // k
r = (n - 1) % k
edges = []
u = 1
for j in range(k):
prv = 0
for i in range(x + 1 if j < r else x):
edges.append((u, prv))
prv = u
u += 1
cost = 2 * x + (2 if r >= 2 else 1 if r >= 1 else 0)
print(cost)
for u, v in edges:
print(u + 1, v + 1)
``` | output | 1 | 73,848 | 13 | 147,697 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability.
Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes.
Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible.
Input
The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes.
Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints.
Output
In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids.
If there are multiple answers, print any of them.
Examples
Input
3 2
Output
2
1 2
2 3
Input
5 3
Output
3
1 2
2 3
3 4
3 5
Note
In the first example the only network is shown on the left picture.
In the second example one of optimal networks is shown on the right picture.
Exit-nodes are highlighted.
<image> | instruction | 0 | 73,849 | 13 | 147,698 |
Tags: constructive algorithms, greedy, implementation, trees
Correct Solution:
```
import math as mt
import sys,string
input=sys.stdin.readline
#print=sys.stdout.write
import random
from collections import deque,defaultdict
L=lambda : list(map(int,input().split()))
Ls=lambda : list(input().split())
M=lambda : map(int,input().split())
I=lambda :int(input())
n,m=M()
if((n-1)%m==0):
ans=2*((n-1)//m)
else:
if((n-1)%m>1):
ans=2*((n-1)//m)+2
else:
ans=2*((n-1)//m)+1
print(ans)
w=(n-1)%m
x=1
for i in range(m):
x+=1
print(1,x)
for j in range((n-1)//m-1):
print(x,x+1)
x+=1
if(w>0):
print(x,x+1)
x+=1
w-=1
``` | output | 1 | 73,849 | 13 | 147,699 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability.
Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes.
Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible.
Input
The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes.
Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints.
Output
In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids.
If there are multiple answers, print any of them.
Examples
Input
3 2
Output
2
1 2
2 3
Input
5 3
Output
3
1 2
2 3
3 4
3 5
Note
In the first example the only network is shown on the left picture.
In the second example one of optimal networks is shown on the right picture.
Exit-nodes are highlighted.
<image> | instruction | 0 | 73,850 | 13 | 147,700 |
Tags: constructive algorithms, greedy, implementation, trees
Correct Solution:
```
n, k = map(int, input().split())
mid = n-k-1
r = [0] * k
for i in range(n-1):
r[i%k] += 1
print(r[0]+r[1])
v1 = 2
ans = []
for i in range(k):
v0 = 1
for _ in range(r[i]):
ans.append("%d %d"%(v0, v1))
v0 = v1
v1 += 1
print("\n".join(ans))
``` | output | 1 | 73,850 | 13 | 147,701 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability.
Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes.
Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible.
Input
The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes.
Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints.
Output
In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids.
If there are multiple answers, print any of them.
Examples
Input
3 2
Output
2
1 2
2 3
Input
5 3
Output
3
1 2
2 3
3 4
3 5
Note
In the first example the only network is shown on the left picture.
In the second example one of optimal networks is shown on the right picture.
Exit-nodes are highlighted.
<image> | instruction | 0 | 73,851 | 13 | 147,702 |
Tags: constructive algorithms, greedy, implementation, trees
Correct Solution:
```
n,k=map(int,input().split())
print(((n-1)//k)*2+min(2,(n-1)%k))
for i in range(2,n+1):
print(i,max(i-k,1))
``` | output | 1 | 73,851 | 13 | 147,703 |
Provide tags and a correct Python 2 solution for this coding contest problem.
Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability.
Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes.
Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible.
Input
The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes.
Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints.
Output
In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids.
If there are multiple answers, print any of them.
Examples
Input
3 2
Output
2
1 2
2 3
Input
5 3
Output
3
1 2
2 3
3 4
3 5
Note
In the first example the only network is shown on the left picture.
In the second example one of optimal networks is shown on the right picture.
Exit-nodes are highlighted.
<image> | instruction | 0 | 73,852 | 13 | 147,704 |
Tags: constructive algorithms, greedy, implementation, trees
Correct Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
mod=10**9+7
def ni():
return int(raw_input())
def li():
return map(int,raw_input().split())
def pn(n):
stdout.write(str(n)+'\n')
def pa(arr):
pr(' '.join(map(str,arr))+'\n')
# fast read function for total integer input
def inp():
# this function returns whole input of
# space/line seperated integers
# Use Ctrl+D to flush stdin.
return map(int,stdin.read().split())
range = xrange # not for python 3.0+
# main code
n,k=li()
n-=1
if n%k==0:
pn(2*(n/k))
elif n%k==1:
pn(2*(n/k)+1)
else:
pn(2*(n/k)+2)
c=n%k
pos=2
for i in range(k):
prev=1
for j in range((n/k)+int(bool(c))):
pa([prev,pos])
prev=pos
pos+=1
if c:
c-=1
``` | output | 1 | 73,852 | 13 | 147,705 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which reads two sequences of nodes obtained by the preorder tree walk and the inorder tree walk on a binary tree respectively, and prints a sequence of the nodes obtained by the postorder tree walk on the binary tree.
Constraints
* $1 \leq n \leq 40$
Input
In the first line, an integer $n$, which is the number of nodes in the binary tree, is given.
In the second line, the sequence of node IDs obtained by the preorder tree walk is given separated by space characters.
In the second line, the sequence of node IDs obtained by the inorder tree walk is given separated by space characters.
Every node has a unique ID from $1$ to $n$. Note that the root does not always correspond to $1$.
Output
Print the sequence of node IDs obtained by the postorder tree walk in a line. Put a single space character between adjacent IDs.
Examples
Input
5
1 2 3 4 5
3 2 4 1 5
Output
3 4 2 5 1
Input
4
1 2 3 4
1 2 3 4
Output
4 3 2 1 | instruction | 0 | 74,149 | 13 | 148,298 |
"Correct Solution:
```
n = int(input())
pretree = list(map(int, input().split()))
inotree = list(map(int, input().split()))
def get_postorder(pre, ino):
if not pre:
return []
root = pre[0]
root_index = ino.index(root)
result = []
result.extend(get_postorder(pre[1:root_index + 1], ino[:root_index]))
result.extend(get_postorder(pre[root_index + 1:], ino[root_index + 1:]))
result.append(root)
return result
print(*get_postorder(pretree, inotree))
``` | output | 1 | 74,149 | 13 | 148,299 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which reads two sequences of nodes obtained by the preorder tree walk and the inorder tree walk on a binary tree respectively, and prints a sequence of the nodes obtained by the postorder tree walk on the binary tree.
Constraints
* $1 \leq n \leq 40$
Input
In the first line, an integer $n$, which is the number of nodes in the binary tree, is given.
In the second line, the sequence of node IDs obtained by the preorder tree walk is given separated by space characters.
In the second line, the sequence of node IDs obtained by the inorder tree walk is given separated by space characters.
Every node has a unique ID from $1$ to $n$. Note that the root does not always correspond to $1$.
Output
Print the sequence of node IDs obtained by the postorder tree walk in a line. Put a single space character between adjacent IDs.
Examples
Input
5
1 2 3 4 5
3 2 4 1 5
Output
3 4 2 5 1
Input
4
1 2 3 4
1 2 3 4
Output
4 3 2 1 | instruction | 0 | 74,150 | 13 | 148,300 |
"Correct Solution:
```
I = 0
L = 1
R = 2
P = 3
B = 4
D = 5
H = 6
def getidx(Tree,value):
idx = -1
for i in range(len(Tree)):
if Tree[i][I] == value:
idx = i
break
return idx
def search(Tree, A, B, num):
root = A[0]
rootidx = getidx(Tree,root)
ld = num
for i in range(num):
if B[i] == root:
ld = i
break
if ld > 0:
left,lidx = search(Tree,A[1:ld+1],B[:ld],ld)
Tree[rootidx][L] = lidx
rt = ld + 1
if rt < num:
right,ridx = search(Tree,A[rt:],B[rt:],num - rt)
Tree[rootidx][R] = ridx
return (root,rootidx)
def postorder(Tree, nidx, A):
if nidx < 0:
return
postorder(Tree,Tree[nidx][L],A)
postorder(Tree,Tree[nidx][R],A)
A.append(Tree[nidx][I])
def main():
""" ????????? """
num = int(input().strip())
plist = list(map(int,input().split()))
ilist = list(map(int,input().split()))
tree = []
for i in plist:
tree.append([i, -1, -1, -1, -1, 0, 0])
root,ridx = search(tree, plist, ilist, num)
pos = []
postorder(tree, ridx, pos)
print(" ".join(map(str,pos)))
if __name__ == '__main__':
main()
``` | output | 1 | 74,150 | 13 | 148,301 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which reads two sequences of nodes obtained by the preorder tree walk and the inorder tree walk on a binary tree respectively, and prints a sequence of the nodes obtained by the postorder tree walk on the binary tree.
Constraints
* $1 \leq n \leq 40$
Input
In the first line, an integer $n$, which is the number of nodes in the binary tree, is given.
In the second line, the sequence of node IDs obtained by the preorder tree walk is given separated by space characters.
In the second line, the sequence of node IDs obtained by the inorder tree walk is given separated by space characters.
Every node has a unique ID from $1$ to $n$. Note that the root does not always correspond to $1$.
Output
Print the sequence of node IDs obtained by the postorder tree walk in a line. Put a single space character between adjacent IDs.
Examples
Input
5
1 2 3 4 5
3 2 4 1 5
Output
3 4 2 5 1
Input
4
1 2 3 4
1 2 3 4
Output
4 3 2 1 | instruction | 0 | 74,151 | 13 | 148,302 |
"Correct Solution:
```
nil = -1
class Node:
def __init__(self):
self.parent = nil
self.left = nil
self.right = nil
def post_tw(node, ans):
if tree[node].left != nil:
post_tw(tree[node].left, ans)
if tree[node].right != nil:
post_tw(tree[node].right, ans)
ans.append(node + 1)
def reconst_tree(node, pretw_itr, subt):
n_i = subt.index(node)
left_subt = subt[:n_i]
right_subt = subt[n_i + 1:]
if left_subt:
left = next(pretw_itr)
tree[node].left = left
reconst_tree(left, pretw_itr, left_subt)
if right_subt:
right = next(pretw_itr)
tree[node].right = right
reconst_tree(right, pretw_itr, right_subt)
n = int(input())
tree = [Node() for i in range(n)]
pretw = [int(i) - 1 for i in input().split()]
intw = [int(i) - 1 for i in input().split()]
pretw_itr = iter(pretw)
root = next(pretw_itr)
reconst_tree(root, pretw_itr, intw)
ans = []
post_tw(root, ans)
print(*ans)
``` | output | 1 | 74,151 | 13 | 148,303 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which reads two sequences of nodes obtained by the preorder tree walk and the inorder tree walk on a binary tree respectively, and prints a sequence of the nodes obtained by the postorder tree walk on the binary tree.
Constraints
* $1 \leq n \leq 40$
Input
In the first line, an integer $n$, which is the number of nodes in the binary tree, is given.
In the second line, the sequence of node IDs obtained by the preorder tree walk is given separated by space characters.
In the second line, the sequence of node IDs obtained by the inorder tree walk is given separated by space characters.
Every node has a unique ID from $1$ to $n$. Note that the root does not always correspond to $1$.
Output
Print the sequence of node IDs obtained by the postorder tree walk in a line. Put a single space character between adjacent IDs.
Examples
Input
5
1 2 3 4 5
3 2 4 1 5
Output
3 4 2 5 1
Input
4
1 2 3 4
1 2 3 4
Output
4 3 2 1 | instruction | 0 | 74,152 | 13 | 148,304 |
"Correct Solution:
```
n=int(input())
preorder=[int(i)for i in input().split()]
inorder=[int(i)for i in input().split()]
post=[]
pos=0
def recon(left,right):
global inorder
global pos
if left>=right:
return
root=preorder[pos]
pos+=1
mid=inorder.index(root)
recon(left,mid)
recon(mid+1,right)
post.append(str(root))
recon(0,n)
print(" ".join(post))
``` | output | 1 | 74,152 | 13 | 148,305 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which reads two sequences of nodes obtained by the preorder tree walk and the inorder tree walk on a binary tree respectively, and prints a sequence of the nodes obtained by the postorder tree walk on the binary tree.
Constraints
* $1 \leq n \leq 40$
Input
In the first line, an integer $n$, which is the number of nodes in the binary tree, is given.
In the second line, the sequence of node IDs obtained by the preorder tree walk is given separated by space characters.
In the second line, the sequence of node IDs obtained by the inorder tree walk is given separated by space characters.
Every node has a unique ID from $1$ to $n$. Note that the root does not always correspond to $1$.
Output
Print the sequence of node IDs obtained by the postorder tree walk in a line. Put a single space character between adjacent IDs.
Examples
Input
5
1 2 3 4 5
3 2 4 1 5
Output
3 4 2 5 1
Input
4
1 2 3 4
1 2 3 4
Output
4 3 2 1 | instruction | 0 | 74,153 | 13 | 148,306 |
"Correct Solution:
```
def reconstract(l, r):
if l >= r:
return None
c = next(root)
m = in_hoge.index(c)
reconstract(l, m)
reconstract(m+1, r)
post_hoge.append(c)
if __name__ == '__main__':
_ = int(input())
pre_hoge = [int(x) for x in input().split()]
root = (x for x in pre_hoge)
in_hoge = [int(x) for x in input().split()]
post_hoge = list()
reconstract(0, len(pre_hoge))
print(' '.join([str(x) for x in post_hoge]))
``` | output | 1 | 74,153 | 13 | 148,307 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which reads two sequences of nodes obtained by the preorder tree walk and the inorder tree walk on a binary tree respectively, and prints a sequence of the nodes obtained by the postorder tree walk on the binary tree.
Constraints
* $1 \leq n \leq 40$
Input
In the first line, an integer $n$, which is the number of nodes in the binary tree, is given.
In the second line, the sequence of node IDs obtained by the preorder tree walk is given separated by space characters.
In the second line, the sequence of node IDs obtained by the inorder tree walk is given separated by space characters.
Every node has a unique ID from $1$ to $n$. Note that the root does not always correspond to $1$.
Output
Print the sequence of node IDs obtained by the postorder tree walk in a line. Put a single space character between adjacent IDs.
Examples
Input
5
1 2 3 4 5
3 2 4 1 5
Output
3 4 2 5 1
Input
4
1 2 3 4
1 2 3 4
Output
4 3 2 1 | instruction | 0 | 74,154 | 13 | 148,308 |
"Correct Solution:
```
pos = 0
def reconstruction(pre_order, in_order, post_order, left, right):
if left >= right:
return
global pos
root = pre_order[pos]
pos += 1
mid = in_order.index(root)
reconstruction(pre_order, in_order, post_order, left, mid)
reconstruction(pre_order, in_order, post_order, mid + 1, right)
post_order.append(root)
def solve(pre_order, in_order):
post_order = []
reconstruction(pre_order, in_order, post_order, 0, len(pre_order))
print(' '.join([str(v) for v in post_order]))
n = int(input())
pre_order = [int(v) for v in input().split()]
in_order = [int(v) for v in input().split()]
solve(pre_order, in_order)
``` | output | 1 | 74,154 | 13 | 148,309 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which reads two sequences of nodes obtained by the preorder tree walk and the inorder tree walk on a binary tree respectively, and prints a sequence of the nodes obtained by the postorder tree walk on the binary tree.
Constraints
* $1 \leq n \leq 40$
Input
In the first line, an integer $n$, which is the number of nodes in the binary tree, is given.
In the second line, the sequence of node IDs obtained by the preorder tree walk is given separated by space characters.
In the second line, the sequence of node IDs obtained by the inorder tree walk is given separated by space characters.
Every node has a unique ID from $1$ to $n$. Note that the root does not always correspond to $1$.
Output
Print the sequence of node IDs obtained by the postorder tree walk in a line. Put a single space character between adjacent IDs.
Examples
Input
5
1 2 3 4 5
3 2 4 1 5
Output
3 4 2 5 1
Input
4
1 2 3 4
1 2 3 4
Output
4 3 2 1 | instruction | 0 | 74,155 | 13 | 148,310 |
"Correct Solution:
```
# Tree Walk
N = int(input())
*A, = map(int, input().split())
*B, = map(int, input().split())
idx = 0
ans = []
def rec(l=0, r=N):
global idx
if l >= r:
return
c = A[idx]
idx += 1
m = B.index(c)
rec(l, m)
rec(m+1, r)
ans.append(c)
rec()
print(*ans)
``` | output | 1 | 74,155 | 13 | 148,311 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which reads two sequences of nodes obtained by the preorder tree walk and the inorder tree walk on a binary tree respectively, and prints a sequence of the nodes obtained by the postorder tree walk on the binary tree.
Constraints
* $1 \leq n \leq 40$
Input
In the first line, an integer $n$, which is the number of nodes in the binary tree, is given.
In the second line, the sequence of node IDs obtained by the preorder tree walk is given separated by space characters.
In the second line, the sequence of node IDs obtained by the inorder tree walk is given separated by space characters.
Every node has a unique ID from $1$ to $n$. Note that the root does not always correspond to $1$.
Output
Print the sequence of node IDs obtained by the postorder tree walk in a line. Put a single space character between adjacent IDs.
Examples
Input
5
1 2 3 4 5
3 2 4 1 5
Output
3 4 2 5 1
Input
4
1 2 3 4
1 2 3 4
Output
4 3 2 1 | instruction | 0 | 74,156 | 13 | 148,312 |
"Correct Solution:
```
def reconstruction(left, right):
if left >= right:
return
global position, pre, ino, post
root = pre[position]
position += 1
mid = ino.index(root) # inoでのrootのポジション
reconstruction(left, mid)
reconstruction(mid + 1, right)
post.append(root)
n = int(input())
pre = list(map(int, input().split()))
ino = list(map(int, input().split()))
post = []
position = 0
reconstruction(0, n)
print(' '.join(map(str, post)))
``` | output | 1 | 74,156 | 13 | 148,313 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which reads two sequences of nodes obtained by the preorder tree walk and the inorder tree walk on a binary tree respectively, and prints a sequence of the nodes obtained by the postorder tree walk on the binary tree.
Constraints
* $1 \leq n \leq 40$
Input
In the first line, an integer $n$, which is the number of nodes in the binary tree, is given.
In the second line, the sequence of node IDs obtained by the preorder tree walk is given separated by space characters.
In the second line, the sequence of node IDs obtained by the inorder tree walk is given separated by space characters.
Every node has a unique ID from $1$ to $n$. Note that the root does not always correspond to $1$.
Output
Print the sequence of node IDs obtained by the postorder tree walk in a line. Put a single space character between adjacent IDs.
Examples
Input
5
1 2 3 4 5
3 2 4 1 5
Output
3 4 2 5 1
Input
4
1 2 3 4
1 2 3 4
Output
4 3 2 1
Submitted Solution:
```
#http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_7_D
def postorder(binary_tree, target_index, result):
left = binary_tree[target_index]["left"]
right = binary_tree[target_index]["right"]
if not left == -1:
postorder(binary_tree, left, result)
if not right == -1:
postorder(binary_tree, right, result)
result.append(target_index)
def solve(preorder_list, inorder_list, result):
#print(preorder_list, inorder_list)
if len(inorder_list) == 1:
return inorder_list[0]
parent = preorder_list[0]
left_trees = inorder_list[:inorder_list.index(parent)]
right_tree_index = 1
if left_trees:
result[parent]["left"] = solve(preorder_list[1:], left_trees, result)
right_tree_index = len(left_trees) + 1
right_trees = inorder_list[inorder_list.index(parent) + 1:]
if right_trees:
result[parent]["right"] = solve(preorder_list[right_tree_index:], right_trees, result)
return parent
def reconstruction(preorder_list, inorder_list, node_num):
result = [{"left":-1,"right":-1} for i in range(node_num + 1)]
solve(preorder_list, inorder_list, result)
return result
def main():
node_num = int(input())
preorder_list = [int(a) for a in input().split()]
inorder_list = [int(a) for a in input().split()]
binary_tree = reconstruction(preorder_list, inorder_list, node_num)
postorder_list = []
postorder(binary_tree, preorder_list[0], postorder_list)
print(*postorder_list)
if __name__ == "__main__":
main()
``` | instruction | 0 | 74,157 | 13 | 148,314 |
Yes | output | 1 | 74,157 | 13 | 148,315 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which reads two sequences of nodes obtained by the preorder tree walk and the inorder tree walk on a binary tree respectively, and prints a sequence of the nodes obtained by the postorder tree walk on the binary tree.
Constraints
* $1 \leq n \leq 40$
Input
In the first line, an integer $n$, which is the number of nodes in the binary tree, is given.
In the second line, the sequence of node IDs obtained by the preorder tree walk is given separated by space characters.
In the second line, the sequence of node IDs obtained by the inorder tree walk is given separated by space characters.
Every node has a unique ID from $1$ to $n$. Note that the root does not always correspond to $1$.
Output
Print the sequence of node IDs obtained by the postorder tree walk in a line. Put a single space character between adjacent IDs.
Examples
Input
5
1 2 3 4 5
3 2 4 1 5
Output
3 4 2 5 1
Input
4
1 2 3 4
1 2 3 4
Output
4 3 2 1
Submitted Solution:
```
# -*- coding: utf-8 -*-
from collections import deque
import sys
sys.setrecursionlimit(100000)
if __name__ == '__main__':
n = int(input())
pre = deque([int(i) for i in input().split(" ")])
ino = deque([int(i) for i in input().split(" ")])
post = []
def reconstruction(l, r):
if l >= r:
return
c = pre.popleft()
m = ino.index(c)
reconstruction(l, m)
reconstruction(m+1, r)
post.append(c)
reconstruction(0, n)
print(" ".join(map(str, post)))
``` | instruction | 0 | 74,158 | 13 | 148,316 |
Yes | output | 1 | 74,158 | 13 | 148,317 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which reads two sequences of nodes obtained by the preorder tree walk and the inorder tree walk on a binary tree respectively, and prints a sequence of the nodes obtained by the postorder tree walk on the binary tree.
Constraints
* $1 \leq n \leq 40$
Input
In the first line, an integer $n$, which is the number of nodes in the binary tree, is given.
In the second line, the sequence of node IDs obtained by the preorder tree walk is given separated by space characters.
In the second line, the sequence of node IDs obtained by the inorder tree walk is given separated by space characters.
Every node has a unique ID from $1$ to $n$. Note that the root does not always correspond to $1$.
Output
Print the sequence of node IDs obtained by the postorder tree walk in a line. Put a single space character between adjacent IDs.
Examples
Input
5
1 2 3 4 5
3 2 4 1 5
Output
3 4 2 5 1
Input
4
1 2 3 4
1 2 3 4
Output
4 3 2 1
Submitted Solution:
```
#! /usr/bin/env python3
# # -*- coding: utf-8 -*-
class Node:
def __init__(self, val, left, right):
self.val = val
self.left = left
self.right = right
def __iter__(self):
yield from self.postorder()
def postorder(self):
yield from self.left
yield from self.right
yield self
def reconstruct(preorder, inorder):
if len(preorder) == 0:
return []
root_val = preorder[0]
root_index = inorder.index(root_val)
inorder_left = inorder[:root_index]
inorder_right = inorder[root_index + 1 :]
preorder_left = [x for x in preorder if x in inorder_left]
preorder_right = [x for x in preorder if x in inorder_right]
return Node(
root_val,
reconstruct(preorder_left, inorder_left),
reconstruct(preorder_right, inorder_right),
)
def main():
n = int(input())
preorder = [int(x) for x in input().split()]
inorder = [int(x) for x in input().split()]
print(*[node.val for node in reconstruct(preorder, inorder).postorder()])
main()
``` | instruction | 0 | 74,159 | 13 | 148,318 |
Yes | output | 1 | 74,159 | 13 | 148,319 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which reads two sequences of nodes obtained by the preorder tree walk and the inorder tree walk on a binary tree respectively, and prints a sequence of the nodes obtained by the postorder tree walk on the binary tree.
Constraints
* $1 \leq n \leq 40$
Input
In the first line, an integer $n$, which is the number of nodes in the binary tree, is given.
In the second line, the sequence of node IDs obtained by the preorder tree walk is given separated by space characters.
In the second line, the sequence of node IDs obtained by the inorder tree walk is given separated by space characters.
Every node has a unique ID from $1$ to $n$. Note that the root does not always correspond to $1$.
Output
Print the sequence of node IDs obtained by the postorder tree walk in a line. Put a single space character between adjacent IDs.
Examples
Input
5
1 2 3 4 5
3 2 4 1 5
Output
3 4 2 5 1
Input
4
1 2 3 4
1 2 3 4
Output
4 3 2 1
Submitted Solution:
```
#coding:UTF-8
def RoT(A,B,ans):
if A:
root=A[0]
rindex=B.index(root)
Aleft=A[1:rindex+1]
Aright=A[rindex+1:]
Bleft=B[:rindex]
Bright=B[rindex+1:]
RoT(Aleft,Bleft,ans)
RoT(Aright,Bright,ans)
ans.append(root)
if __name__=="__main__":
n=int(input())
A=input().split(" ")
B=input().split(" ")
ans=[]
RoT(A,B,ans)
print(" ".join(ans))
``` | instruction | 0 | 74,160 | 13 | 148,320 |
Yes | output | 1 | 74,160 | 13 | 148,321 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which reads two sequences of nodes obtained by the preorder tree walk and the inorder tree walk on a binary tree respectively, and prints a sequence of the nodes obtained by the postorder tree walk on the binary tree.
Constraints
* $1 \leq n \leq 40$
Input
In the first line, an integer $n$, which is the number of nodes in the binary tree, is given.
In the second line, the sequence of node IDs obtained by the preorder tree walk is given separated by space characters.
In the second line, the sequence of node IDs obtained by the inorder tree walk is given separated by space characters.
Every node has a unique ID from $1$ to $n$. Note that the root does not always correspond to $1$.
Output
Print the sequence of node IDs obtained by the postorder tree walk in a line. Put a single space character between adjacent IDs.
Examples
Input
5
1 2 3 4 5
3 2 4 1 5
Output
3 4 2 5 1
Input
4
1 2 3 4
1 2 3 4
Output
4 3 2 1
Submitted Solution:
```
I = 0
L = 1
R = 2
P = 3
B = 4
D = 5
H = 6
def search(N, A, B, num):
""" N ??? Nodes A???Preorder?????? B???Inorder??????
??????????????????????????§??? root ??? index ????????? """
# print(A)
# print(B)
root = A[0]
ld = num
for i in range(num):
if B[i] == root:
ld = i
break
if ld > 0:
N[root][L] = search(N,A[1:ld+1],B[:ld],ld)
rt = ld + 1
if rt < num:
N[root][R] = search(N,A[rt:],B[rt:],num - rt)
return root
def getroot(A, id):
if A[id][P] > -1:
return getroot(A,A[id][P])
return A[id][I]
def preorder(N,id,A):
if id < 0:
return
A.append(id)
preorder(N,N[id][L],A)
preorder(N,N[id][R],A)
def inorder(N,id,A):
if id < 0:
return
inorder(N,N[id][L],A)
A.append(id)
inorder(N,N[id][R],A)
def postorder(N,id,A):
if id < 0:
return
postorder(N,N[id][L],A)
postorder(N,N[id][R],A)
A.append(id)
def main():
""" ????????? """
num = int(input().strip())
plist = list(map(int,input().split()))
ilist = list(map(int,input().split()))
pos = []
nodes = [[i, -1, -1, -1, -1, 0, 0] for i in range(num)]
search(nodes,plist,ilist,num)
# pre = [""]
# ino = [""]
pos = []
# preorder(nodes,plist[0],pre)
# inorder(nodes,plist[0],ino)
postorder(nodes,plist[0],pos)
# print("Preorder")
# print(" ".join(map(str,pre)))
# print("Inorder")
# print(" ".join(map(str,ino)))
# print("Postorder")
print(" ".join(map(str,pos)))
if __name__ == '__main__':
main()
``` | instruction | 0 | 74,161 | 13 | 148,322 |
No | output | 1 | 74,161 | 13 | 148,323 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which reads two sequences of nodes obtained by the preorder tree walk and the inorder tree walk on a binary tree respectively, and prints a sequence of the nodes obtained by the postorder tree walk on the binary tree.
Constraints
* $1 \leq n \leq 40$
Input
In the first line, an integer $n$, which is the number of nodes in the binary tree, is given.
In the second line, the sequence of node IDs obtained by the preorder tree walk is given separated by space characters.
In the second line, the sequence of node IDs obtained by the inorder tree walk is given separated by space characters.
Every node has a unique ID from $1$ to $n$. Note that the root does not always correspond to $1$.
Output
Print the sequence of node IDs obtained by the postorder tree walk in a line. Put a single space character between adjacent IDs.
Examples
Input
5
1 2 3 4 5
3 2 4 1 5
Output
3 4 2 5 1
Input
4
1 2 3 4
1 2 3 4
Output
4 3 2 1
Submitted Solution:
```
I = 0
L = 1
R = 2
P = 3
B = 4
D = 5
H = 6
def search(N, A, B, num):
root = A[0]
ld = num
for i in range(num):
if B[i] == root:
ld = i
break
if ld > 0:
N[root][L] = search(N,A[1:ld+1],B[:ld],ld)
rt = ld + 1
if rt < num:
N[root][R] = search(N,A[rt:],B[rt:],num - rt)
return root
def postorder(N,id,A):
if id < 0:
return
postorder(N,N[id][L],A)
postorder(N,N[id][R],A)
A.append(id)
def main():
""" ????????? """
num = int(input().strip())
plist = list(map(int,input().split()))
ilist = list(map(int,input().split()))
pos = []
nodes = [[i, -1, -1, -1, -1, 0, 0] for i in range(num)]
search(nodes,plist,ilist,num)
pos = []
print(" ".join(map(str,pos)))
if __name__ == '__main__':
main()
``` | instruction | 0 | 74,162 | 13 | 148,324 |
No | output | 1 | 74,162 | 13 | 148,325 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which reads two sequences of nodes obtained by the preorder tree walk and the inorder tree walk on a binary tree respectively, and prints a sequence of the nodes obtained by the postorder tree walk on the binary tree.
Constraints
* $1 \leq n \leq 40$
Input
In the first line, an integer $n$, which is the number of nodes in the binary tree, is given.
In the second line, the sequence of node IDs obtained by the preorder tree walk is given separated by space characters.
In the second line, the sequence of node IDs obtained by the inorder tree walk is given separated by space characters.
Every node has a unique ID from $1$ to $n$. Note that the root does not always correspond to $1$.
Output
Print the sequence of node IDs obtained by the postorder tree walk in a line. Put a single space character between adjacent IDs.
Examples
Input
5
1 2 3 4 5
3 2 4 1 5
Output
3 4 2 5 1
Input
4
1 2 3 4
1 2 3 4
Output
4 3 2 1
Submitted Solution:
```
class Tree:
__slots__ = ['id', 'p', 'left', 'right']
def __init__(self, id):
self.id = id
self.left = -1
self.right = -1
def setc(self, c):
if self.left == -1:
self.left = c
else:
self.right = c
def __str__(self):
return f"node {self.id}: left = {self.left}, right = {self.right}"
n = int(input())
tree = tuple(Tree(i) for i in range(n + 1))
pretree = list(map(int, input().split()))
inotree = list(map(int, input().split()))
root = pretree[0]
root_index = inotree.index(root)
SET = set(pretree) - {root}
ans = []
def treeSet(A, i):
if len(A) == 0:
return
global SET
c = root
r = pretree.index(A[0])
for a in pretree[i: r + 1]:
if c != a:
SET -= {a}
tree[c].setc(a)
c = a
for b in A[1:]:
if b not in SET:
c = b
continue
SET.add(b)
tree[c].setc(b)
c = b
treeSet(inotree[:root_index], 0)
treeSet(inotree[root_index + 1:], root_index + 1)
def postorder_tree_walk(id):
if tree[id].left != -1:
postorder_tree_walk(tree[id].left)
if tree[id].right != -1:
postorder_tree_walk(tree[id].right)
global ans
ans.append(id)
postorder_tree_walk(root)
print(*ans)
``` | instruction | 0 | 74,163 | 13 | 148,326 |
No | output | 1 | 74,163 | 13 | 148,327 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which reads two sequences of nodes obtained by the preorder tree walk and the inorder tree walk on a binary tree respectively, and prints a sequence of the nodes obtained by the postorder tree walk on the binary tree.
Constraints
* $1 \leq n \leq 40$
Input
In the first line, an integer $n$, which is the number of nodes in the binary tree, is given.
In the second line, the sequence of node IDs obtained by the preorder tree walk is given separated by space characters.
In the second line, the sequence of node IDs obtained by the inorder tree walk is given separated by space characters.
Every node has a unique ID from $1$ to $n$. Note that the root does not always correspond to $1$.
Output
Print the sequence of node IDs obtained by the postorder tree walk in a line. Put a single space character between adjacent IDs.
Examples
Input
5
1 2 3 4 5
3 2 4 1 5
Output
3 4 2 5 1
Input
4
1 2 3 4
1 2 3 4
Output
4 3 2 1
Submitted Solution:
```
n = int(input())
tree = [None for i in range(n +1)]
list_pre = list(map(int, input().split()))
list_in = list(map(int, input().split()))
def reconstruct(tree_pre, tree_in):
if not tree_pre:
return -1
root = tree_pre[0]
idx = tree_in.index(root)
tree[root] = (reconstruct(tree_pre[1:i + 1], tree_in[:i]),
reconstruct(tree_pre[i + 1:], tree_in[i + 1:]))
return root
def post_order_search(i):
if i == -1:
return
l, r = tree[i]
for j in post_order_search(l):
yield j
for j in post_order_search(r):
yield j
yield i
solve(list_pre, list_in)
print(*postorder(list_pre[0]))
``` | instruction | 0 | 74,164 | 13 | 148,328 |
No | output | 1 | 74,164 | 13 | 148,329 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider a tree T (that is, a connected graph without cycles) with n vertices labelled 1 through n. We start the following process with T: while T has more than one vertex, do the following:
* choose a random edge of T equiprobably;
* shrink the chosen edge: if the edge was connecting vertices v and u, erase both v and u and create a new vertex adjacent to all vertices previously adjacent to either v or u. The new vertex is labelled either v or u equiprobably.
At the end of the process, T consists of a single vertex labelled with one of the numbers 1, …, n. For each of the numbers, what is the probability of this number becoming the label of the final vertex?
Input
The first line contains a single integer n (1 ≤ n ≤ 50).
The following n - 1 lines describe the tree edges. Each of these lines contains two integers u_i, v_i — labels of vertices connected by the respective edge (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i). It is guaranteed that the given graph is a tree.
Output
Print n floating numbers — the desired probabilities for labels 1, …, n respectively. All numbers should be correct up to 10^{-6} relative or absolute precision.
Examples
Input
4
1 2
1 3
1 4
Output
0.1250000000
0.2916666667
0.2916666667
0.2916666667
Input
7
1 2
1 3
2 4
2 5
3 6
3 7
Output
0.0850694444
0.0664062500
0.0664062500
0.1955295139
0.1955295139
0.1955295139
0.1955295139
Note
In the first sample, the resulting vertex has label 1 if and only if for all three edges the label 1 survives, hence the probability is 1/2^3 = 1/8. All other labels have equal probability due to symmetry, hence each of them has probability (1 - 1/8) / 3 = 7/24. | instruction | 0 | 74,197 | 13 | 148,394 |
Tags: combinatorics, dp
Correct Solution:
```
maxn=50+10
g=[None]*maxn
dp=[None]*maxn
c=[None]*maxn
size=[0]*maxn
for i in range(0,maxn):
c[i]=[0]*maxn
c[i][0]=1
for j in range(1,i+1):
c[i][j]=c[i-1][j-1]+c[i-1][j]
n=int(input())
for i in range(1,n+1):
g[i]=[]
for i in range(1,n):
u,v=input().split()
u=int(u)
v=int(v)
g[u].append(v)
g[v].append(u)
def mul(a,b,x,y):
tmp=[0]*(x+y+1)
for i in range(0,x+1):
for j in range(0,y+1):
tmp[i+j]+=a[i]*b[j]*c[i+j][i]*c[x+y-i-j][x-i]
return tmp
def dfs(pos,fa):
global dp
global size
dp[pos]=[1]
size[pos]=0
for ch in g[pos]:
if ch != fa:
dfs(pos=ch,fa=pos)
dp[pos]=mul(dp[pos],dp[ch],size[pos],size[ch])
size[pos]+=size[ch]
if fa:
size[pos]+=1
tmp=[0]*(size[pos]+1)
for i in range(0,size[pos]+1):
for j in range(0,size[pos]):
if j<i:
tmp[i]+=dp[pos][i-1]
else:
tmp[i]+=dp[pos][j]*0.5
dp[pos]=tmp
for i in range(1,n+1):
dfs(pos=i,fa=0)
tmp=dp[i][0]
for j in range(1,n):
tmp/=j
print(tmp)
``` | output | 1 | 74,197 | 13 | 148,395 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Graph constructive problems are back! This time the graph you are asked to build should match the following properties.
The graph is connected if and only if there exists a path between every pair of vertices.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
The degree of a vertex is the number of edges incident to it.
Given a sequence of n integers a_1, a_2, ..., a_n construct a connected undirected graph of n vertices such that:
* the graph contains no self-loops and no multiple edges;
* the degree d_i of the i-th vertex doesn't exceed a_i (i.e. d_i ≤ a_i);
* the diameter of the graph is maximum possible.
Output the resulting graph or report that no solution exists.
Input
The first line contains a single integer n (3 ≤ n ≤ 500) — the number of vertices in the graph.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n - 1) — the upper limits to vertex degrees.
Output
Print "NO" if no graph can be constructed under the given conditions.
Otherwise print "YES" and the diameter of the resulting graph in the first line.
The second line should contain a single integer m — the number of edges in the resulting graph.
The i-th of the next m lines should contain two integers v_i, u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the description of the i-th edge. The graph should contain no multiple edges — for each pair (x, y) you output, you should output no more pairs (x, y) or (y, x).
Examples
Input
3
2 2 2
Output
YES 2
2
1 2
2 3
Input
5
1 4 1 1 1
Output
YES 2
4
1 2
3 2
4 2
5 2
Input
3
1 1 1
Output
NO
Note
Here are the graphs for the first two example cases. Both have diameter of 2.
<image> d_1 = 1 ≤ a_1 = 2
d_2 = 2 ≤ a_2 = 2
d_3 = 1 ≤ a_3 = 2
<image> d_1 = 1 ≤ a_1 = 1
d_2 = 4 ≤ a_2 = 4
d_3 = 1 ≤ a_3 = 1
d_4 = 1 ≤ a_4 = 1 | instruction | 0 | 74,198 | 13 | 148,396 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
def out_edge(x,y):
a[x] -= 1
a[y] -= 1
print(x,y)
n = int(input())
a =list(map(int, input().split()))
sa = sum(a)
ma = min(a)
if (sa <2*(n-1)) or (ma<1):
print('NO')
exit()
verts = sorted(enumerate(a,1), key = lambda x: x[1], reverse= True)
verts = [list(j) for j in verts]
outres = []
for kk in range(1,n):
if verts[kk-1][1] >= 1:
outres.append((verts[kk] [0], verts[kk-1][0]))
verts[kk][1] -= 1
verts[kk-1][1] -= 1
else:
break
else:
kk+=1
path_len = kk
# print(kk)
print('YES', min(n-1, path_len))
reserve_start = 0
while kk < n:
if verts[reserve_start][1] >0:
outres.append((verts[reserve_start][0], verts[kk][0]))
verts[reserve_start][1] -= 1
verts[kk][1] -= 1
kk +=1
else:
reserve_start += 1
print(len(outres))
for oo in outres:
print(*oo)
``` | output | 1 | 74,198 | 13 | 148,397 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Graph constructive problems are back! This time the graph you are asked to build should match the following properties.
The graph is connected if and only if there exists a path between every pair of vertices.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
The degree of a vertex is the number of edges incident to it.
Given a sequence of n integers a_1, a_2, ..., a_n construct a connected undirected graph of n vertices such that:
* the graph contains no self-loops and no multiple edges;
* the degree d_i of the i-th vertex doesn't exceed a_i (i.e. d_i ≤ a_i);
* the diameter of the graph is maximum possible.
Output the resulting graph or report that no solution exists.
Input
The first line contains a single integer n (3 ≤ n ≤ 500) — the number of vertices in the graph.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n - 1) — the upper limits to vertex degrees.
Output
Print "NO" if no graph can be constructed under the given conditions.
Otherwise print "YES" and the diameter of the resulting graph in the first line.
The second line should contain a single integer m — the number of edges in the resulting graph.
The i-th of the next m lines should contain two integers v_i, u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the description of the i-th edge. The graph should contain no multiple edges — for each pair (x, y) you output, you should output no more pairs (x, y) or (y, x).
Examples
Input
3
2 2 2
Output
YES 2
2
1 2
2 3
Input
5
1 4 1 1 1
Output
YES 2
4
1 2
3 2
4 2
5 2
Input
3
1 1 1
Output
NO
Note
Here are the graphs for the first two example cases. Both have diameter of 2.
<image> d_1 = 1 ≤ a_1 = 2
d_2 = 2 ≤ a_2 = 2
d_3 = 1 ≤ a_3 = 2
<image> d_1 = 1 ≤ a_1 = 1
d_2 = 4 ≤ a_2 = 4
d_3 = 1 ≤ a_3 = 1
d_4 = 1 ≤ a_4 = 1 | instruction | 0 | 74,199 | 13 | 148,398 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
from collections import namedtuple
vertex = namedtuple('vertex', ['degree', 'id'])
a, b, c = [], [], 0
n = int(input())
rr = list(map(int, input().split()))
for i in range(n):
if rr[i] > 1:
a.append(vertex(rr[i], i + 1))
else:
b.append(vertex(rr[i], i + 1))
c += rr[i]
if c < (n - 1)*2:
print('NO')
else:
print('YES', len(a) - 1 + min(2, len(b)))
print(n - 1)
for i in range(1,len(a)):
print(a[i - 1].id, a[i].id)
if len(b) > 0:
print(b[0].id, a[0].id)
if len(b) > 1:
print(b[1].id, a[-1].id)
j, yes = 2, 0
for i in range(len(a)):
k = a[i].degree - 2
for t in range(k):
if j >= len(b):
yes = 1
break
print(a[i].id, b[j].id)
j += 1
if yes == 1:
break
``` | output | 1 | 74,199 | 13 | 148,399 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Graph constructive problems are back! This time the graph you are asked to build should match the following properties.
The graph is connected if and only if there exists a path between every pair of vertices.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
The degree of a vertex is the number of edges incident to it.
Given a sequence of n integers a_1, a_2, ..., a_n construct a connected undirected graph of n vertices such that:
* the graph contains no self-loops and no multiple edges;
* the degree d_i of the i-th vertex doesn't exceed a_i (i.e. d_i ≤ a_i);
* the diameter of the graph is maximum possible.
Output the resulting graph or report that no solution exists.
Input
The first line contains a single integer n (3 ≤ n ≤ 500) — the number of vertices in the graph.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n - 1) — the upper limits to vertex degrees.
Output
Print "NO" if no graph can be constructed under the given conditions.
Otherwise print "YES" and the diameter of the resulting graph in the first line.
The second line should contain a single integer m — the number of edges in the resulting graph.
The i-th of the next m lines should contain two integers v_i, u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the description of the i-th edge. The graph should contain no multiple edges — for each pair (x, y) you output, you should output no more pairs (x, y) or (y, x).
Examples
Input
3
2 2 2
Output
YES 2
2
1 2
2 3
Input
5
1 4 1 1 1
Output
YES 2
4
1 2
3 2
4 2
5 2
Input
3
1 1 1
Output
NO
Note
Here are the graphs for the first two example cases. Both have diameter of 2.
<image> d_1 = 1 ≤ a_1 = 2
d_2 = 2 ≤ a_2 = 2
d_3 = 1 ≤ a_3 = 2
<image> d_1 = 1 ≤ a_1 = 1
d_2 = 4 ≤ a_2 = 4
d_3 = 1 ≤ a_3 = 1
d_4 = 1 ≤ a_4 = 1 | instruction | 0 | 74,200 | 13 | 148,400 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
n = int(input())
a = tuple(map(int, input().split()))
if n * 2 > sum(a) + 2:
print("NO")
else:
n1 = []
on = []
for i in range(n):
if a[i] != 1:
n1.append(i)
else:
on.append(i)
print("YES", len(n1) + min(2, len(on)) - 1)
print(n - 1)
n1it = iter(n1)
next(n1it)
for v, u in zip(n1, n1it):
print(v + 1, u + 1)
if on:
print(on.pop() + 1, n1[-1] + 1)
if on:
print(on.pop() + 1, n1[0] + 1)
on = iter(on)
for n11 in n1:
for i in range(a[n11] - 2):
try:
print(n11 + 1, next(on) + 1)
except StopIteration:
break
else:
continue
break
``` | output | 1 | 74,200 | 13 | 148,401 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Graph constructive problems are back! This time the graph you are asked to build should match the following properties.
The graph is connected if and only if there exists a path between every pair of vertices.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
The degree of a vertex is the number of edges incident to it.
Given a sequence of n integers a_1, a_2, ..., a_n construct a connected undirected graph of n vertices such that:
* the graph contains no self-loops and no multiple edges;
* the degree d_i of the i-th vertex doesn't exceed a_i (i.e. d_i ≤ a_i);
* the diameter of the graph is maximum possible.
Output the resulting graph or report that no solution exists.
Input
The first line contains a single integer n (3 ≤ n ≤ 500) — the number of vertices in the graph.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n - 1) — the upper limits to vertex degrees.
Output
Print "NO" if no graph can be constructed under the given conditions.
Otherwise print "YES" and the diameter of the resulting graph in the first line.
The second line should contain a single integer m — the number of edges in the resulting graph.
The i-th of the next m lines should contain two integers v_i, u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the description of the i-th edge. The graph should contain no multiple edges — for each pair (x, y) you output, you should output no more pairs (x, y) or (y, x).
Examples
Input
3
2 2 2
Output
YES 2
2
1 2
2 3
Input
5
1 4 1 1 1
Output
YES 2
4
1 2
3 2
4 2
5 2
Input
3
1 1 1
Output
NO
Note
Here are the graphs for the first two example cases. Both have diameter of 2.
<image> d_1 = 1 ≤ a_1 = 2
d_2 = 2 ≤ a_2 = 2
d_3 = 1 ≤ a_3 = 2
<image> d_1 = 1 ≤ a_1 = 1
d_2 = 4 ≤ a_2 = 4
d_3 = 1 ≤ a_3 = 1
d_4 = 1 ≤ a_4 = 1 | instruction | 0 | 74,201 | 13 | 148,402 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
n = int(input())
A = [0] + list(map(int,input().split()))
vec = []
for i in range(1, n+1) :
vec = vec + [[A[i], i]]
list.sort(vec)
list.reverse(vec)
# print(vec)
if vec[0][0] == 1 :
print("NO")
exit(0)
dia = 0
path = [vec[0][1]]
ans = []
bol, col, idx = 1, 1, 0
for i in vec[1:] :
# print(i)
if i[0] != 1 :
ans = ans + [[path[-1], i[1]]]
dia = dia+1
A[path[-1]] = A[path[-1]]-1
path += [i[1]];
A[path[-1]] = A[path[-1]]-1
else :
if col == 1:
dia = dia+1
col = 0
A[path[0]] -= 1
ans = ans+ [[path[0], i[1]]]
elif bol == 1:
dia = dia+1
bol = 0
A[path[-1]] -= 1
ans = ans + [[path[-1], i[1]]]
else :
while idx < len(path) and A[path[idx]] == 0 :
idx = idx+1
if idx == len(path) :
print("NO")
exit(0)
A[path[idx]] = A[path[idx]] - 1;
ans = ans + [[path[idx], i[1]]]
print("YES", dia)
print(len(ans))
for i in ans :
print(i[0], i[1])
``` | output | 1 | 74,201 | 13 | 148,403 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Graph constructive problems are back! This time the graph you are asked to build should match the following properties.
The graph is connected if and only if there exists a path between every pair of vertices.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
The degree of a vertex is the number of edges incident to it.
Given a sequence of n integers a_1, a_2, ..., a_n construct a connected undirected graph of n vertices such that:
* the graph contains no self-loops and no multiple edges;
* the degree d_i of the i-th vertex doesn't exceed a_i (i.e. d_i ≤ a_i);
* the diameter of the graph is maximum possible.
Output the resulting graph or report that no solution exists.
Input
The first line contains a single integer n (3 ≤ n ≤ 500) — the number of vertices in the graph.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n - 1) — the upper limits to vertex degrees.
Output
Print "NO" if no graph can be constructed under the given conditions.
Otherwise print "YES" and the diameter of the resulting graph in the first line.
The second line should contain a single integer m — the number of edges in the resulting graph.
The i-th of the next m lines should contain two integers v_i, u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the description of the i-th edge. The graph should contain no multiple edges — for each pair (x, y) you output, you should output no more pairs (x, y) or (y, x).
Examples
Input
3
2 2 2
Output
YES 2
2
1 2
2 3
Input
5
1 4 1 1 1
Output
YES 2
4
1 2
3 2
4 2
5 2
Input
3
1 1 1
Output
NO
Note
Here are the graphs for the first two example cases. Both have diameter of 2.
<image> d_1 = 1 ≤ a_1 = 2
d_2 = 2 ≤ a_2 = 2
d_3 = 1 ≤ a_3 = 2
<image> d_1 = 1 ≤ a_1 = 1
d_2 = 4 ≤ a_2 = 4
d_3 = 1 ≤ a_3 = 1
d_4 = 1 ≤ a_4 = 1 | instruction | 0 | 74,202 | 13 | 148,404 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
n = int(input())
l = list(map(int, input().split()))
one,many = [],[]
a,b,c = 0,0,0
for i,d in enumerate(l):
if d==1:
one.append(i+1)
a+=1
else:
many.append((i+1,d))
b+=1
c+=d
if c-2*b+2<a:
print("NO")
exit()
print("YES",b+ min(a, min(a,2))-1)
print(n-1)
left = []
dia = []
if one:
dia.append(one.pop())
for i,d in many:
dia.append(i)
if d>2:
left.append((i,d-2))
if one:
dia.append(one.pop())
for i in range(len(dia)-1):
print(dia[i], dia[i+1])
while one:
i,d = left.pop()
print(i, one.pop())
if d>1:
left.append((i,d-1))
``` | output | 1 | 74,202 | 13 | 148,405 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Graph constructive problems are back! This time the graph you are asked to build should match the following properties.
The graph is connected if and only if there exists a path between every pair of vertices.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
The degree of a vertex is the number of edges incident to it.
Given a sequence of n integers a_1, a_2, ..., a_n construct a connected undirected graph of n vertices such that:
* the graph contains no self-loops and no multiple edges;
* the degree d_i of the i-th vertex doesn't exceed a_i (i.e. d_i ≤ a_i);
* the diameter of the graph is maximum possible.
Output the resulting graph or report that no solution exists.
Input
The first line contains a single integer n (3 ≤ n ≤ 500) — the number of vertices in the graph.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n - 1) — the upper limits to vertex degrees.
Output
Print "NO" if no graph can be constructed under the given conditions.
Otherwise print "YES" and the diameter of the resulting graph in the first line.
The second line should contain a single integer m — the number of edges in the resulting graph.
The i-th of the next m lines should contain two integers v_i, u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the description of the i-th edge. The graph should contain no multiple edges — for each pair (x, y) you output, you should output no more pairs (x, y) or (y, x).
Examples
Input
3
2 2 2
Output
YES 2
2
1 2
2 3
Input
5
1 4 1 1 1
Output
YES 2
4
1 2
3 2
4 2
5 2
Input
3
1 1 1
Output
NO
Note
Here are the graphs for the first two example cases. Both have diameter of 2.
<image> d_1 = 1 ≤ a_1 = 2
d_2 = 2 ≤ a_2 = 2
d_3 = 1 ≤ a_3 = 2
<image> d_1 = 1 ≤ a_1 = 1
d_2 = 4 ≤ a_2 = 4
d_3 = 1 ≤ a_3 = 1
d_4 = 1 ≤ a_4 = 1 | instruction | 0 | 74,203 | 13 | 148,406 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
n=int(input())
a=list(map(int,input().split()))
l=[]
for i in range(n):
l.append([a[i],i])
l.sort(key=lambda x:x[0])
for i in range(n):
if l[i][0]>1:
break
j=0
for k in range(i,n):
j+=l[k][0]-2
if j<i-2:
print("NO")
else:
print("YES",n-i+min(2,i)-1)
print(n-1)
k=2
for j in range(i,n-1):
print(l[j][1]+1,l[j+1][1]+1)
if i>0:
print(l[0][1]+1,l[i][1]+1)
if i>1:
print(l[1][1]+1,l[n-1][1]+1)
if i>2:
for j in range(i,n):
if k==i:
break
for p in range(2,l[j][0]):
print(l[k][1]+1,l[j][1]+1)
k+=1
if k==i:
break
``` | output | 1 | 74,203 | 13 | 148,407 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Graph constructive problems are back! This time the graph you are asked to build should match the following properties.
The graph is connected if and only if there exists a path between every pair of vertices.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
The degree of a vertex is the number of edges incident to it.
Given a sequence of n integers a_1, a_2, ..., a_n construct a connected undirected graph of n vertices such that:
* the graph contains no self-loops and no multiple edges;
* the degree d_i of the i-th vertex doesn't exceed a_i (i.e. d_i ≤ a_i);
* the diameter of the graph is maximum possible.
Output the resulting graph or report that no solution exists.
Input
The first line contains a single integer n (3 ≤ n ≤ 500) — the number of vertices in the graph.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n - 1) — the upper limits to vertex degrees.
Output
Print "NO" if no graph can be constructed under the given conditions.
Otherwise print "YES" and the diameter of the resulting graph in the first line.
The second line should contain a single integer m — the number of edges in the resulting graph.
The i-th of the next m lines should contain two integers v_i, u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the description of the i-th edge. The graph should contain no multiple edges — for each pair (x, y) you output, you should output no more pairs (x, y) or (y, x).
Examples
Input
3
2 2 2
Output
YES 2
2
1 2
2 3
Input
5
1 4 1 1 1
Output
YES 2
4
1 2
3 2
4 2
5 2
Input
3
1 1 1
Output
NO
Note
Here are the graphs for the first two example cases. Both have diameter of 2.
<image> d_1 = 1 ≤ a_1 = 2
d_2 = 2 ≤ a_2 = 2
d_3 = 1 ≤ a_3 = 2
<image> d_1 = 1 ≤ a_1 = 1
d_2 = 4 ≤ a_2 = 4
d_3 = 1 ≤ a_3 = 1
d_4 = 1 ≤ a_4 = 1 | instruction | 0 | 74,204 | 13 | 148,408 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
# coding: utf-8
# Your code here!
import sys
n = int(input())
a = list(map(int,input().split()))
for i in range(n):
a[i] = [i,a[i]]
a.sort(key=lambda x: x[1],reverse=True)
ans = []
index = 0
cnt = 0
tmp = 1
right_bool = False
left_bool = False
for i in range(1,n):
if a[index][1] == 0:
print('NO')
sys.exit()
if a[i][1] >= 2:
ans.append([a[i-1][0],a[i][0]])
cnt += 1
a[i-1][1] -= 1
a[i][1] -= 1
else:
if right_bool == False:
ans.append([a[i-1][0],a[i][0]])
a[i-1][1] -= 1
a[i][1] -= 1
cnt += 1
right_bool = True
else:
ans.append([a[index][0],a[i][0]])
a[index][1] -= 1
a[i][1] -= 1
if left_bool == False:
cnt += 1
left_bool = True
if a[index][1] == 0:
index += 1
print('YES', cnt)
print(n-1)
for i in range(n-1):
print(ans[i][0]+1,ans[i][1]+1)
``` | output | 1 | 74,204 | 13 | 148,409 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Graph constructive problems are back! This time the graph you are asked to build should match the following properties.
The graph is connected if and only if there exists a path between every pair of vertices.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
The degree of a vertex is the number of edges incident to it.
Given a sequence of n integers a_1, a_2, ..., a_n construct a connected undirected graph of n vertices such that:
* the graph contains no self-loops and no multiple edges;
* the degree d_i of the i-th vertex doesn't exceed a_i (i.e. d_i ≤ a_i);
* the diameter of the graph is maximum possible.
Output the resulting graph or report that no solution exists.
Input
The first line contains a single integer n (3 ≤ n ≤ 500) — the number of vertices in the graph.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n - 1) — the upper limits to vertex degrees.
Output
Print "NO" if no graph can be constructed under the given conditions.
Otherwise print "YES" and the diameter of the resulting graph in the first line.
The second line should contain a single integer m — the number of edges in the resulting graph.
The i-th of the next m lines should contain two integers v_i, u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the description of the i-th edge. The graph should contain no multiple edges — for each pair (x, y) you output, you should output no more pairs (x, y) or (y, x).
Examples
Input
3
2 2 2
Output
YES 2
2
1 2
2 3
Input
5
1 4 1 1 1
Output
YES 2
4
1 2
3 2
4 2
5 2
Input
3
1 1 1
Output
NO
Note
Here are the graphs for the first two example cases. Both have diameter of 2.
<image> d_1 = 1 ≤ a_1 = 2
d_2 = 2 ≤ a_2 = 2
d_3 = 1 ≤ a_3 = 2
<image> d_1 = 1 ≤ a_1 = 1
d_2 = 4 ≤ a_2 = 4
d_3 = 1 ≤ a_3 = 1
d_4 = 1 ≤ a_4 = 1 | instruction | 0 | 74,205 | 13 | 148,410 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
n=int(input());
deg=list(map(int,input().split()));
sumd=0;
deg_1=[];
deg_2=[];
for i in range(n):
sumd+=deg[i];
if (deg[i]>1):
deg_2.append(i);
else:
deg_1.append(i);
if (sumd<2*n-2):
print("NO");
else:
l1=len(deg_1);
l2=len(deg_2);
while (l1<2):
deg_1.append(deg_2[l2-1]);
l1+=1;
l2-=1;
print("YES %d"%(n+1-l1));
print(n-1);
for i in range(l2-1):
print("%d %d"%(deg_2[i]+1,deg_2[i+1]+1));
deg[deg_2[i]]-=1;
deg[deg_2[i+1]]-=1;
print("%d %d"%(deg_2[l2-1]+1,deg_1[0]+1));
deg[deg_2[l2-1]]-=1;
j=0;
for i in range(1,l1):
while (deg[deg_2[j]]==0):
j+=1;
print("%d %d"%(deg_1[i]+1,deg_2[j]+1));
deg[deg_2[j]]-=1;
``` | output | 1 | 74,205 | 13 | 148,411 |
Provide tags and a correct Python 2 solution for this coding contest problem.
Graph constructive problems are back! This time the graph you are asked to build should match the following properties.
The graph is connected if and only if there exists a path between every pair of vertices.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
The degree of a vertex is the number of edges incident to it.
Given a sequence of n integers a_1, a_2, ..., a_n construct a connected undirected graph of n vertices such that:
* the graph contains no self-loops and no multiple edges;
* the degree d_i of the i-th vertex doesn't exceed a_i (i.e. d_i ≤ a_i);
* the diameter of the graph is maximum possible.
Output the resulting graph or report that no solution exists.
Input
The first line contains a single integer n (3 ≤ n ≤ 500) — the number of vertices in the graph.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n - 1) — the upper limits to vertex degrees.
Output
Print "NO" if no graph can be constructed under the given conditions.
Otherwise print "YES" and the diameter of the resulting graph in the first line.
The second line should contain a single integer m — the number of edges in the resulting graph.
The i-th of the next m lines should contain two integers v_i, u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the description of the i-th edge. The graph should contain no multiple edges — for each pair (x, y) you output, you should output no more pairs (x, y) or (y, x).
Examples
Input
3
2 2 2
Output
YES 2
2
1 2
2 3
Input
5
1 4 1 1 1
Output
YES 2
4
1 2
3 2
4 2
5 2
Input
3
1 1 1
Output
NO
Note
Here are the graphs for the first two example cases. Both have diameter of 2.
<image> d_1 = 1 ≤ a_1 = 2
d_2 = 2 ≤ a_2 = 2
d_3 = 1 ≤ a_3 = 2
<image> d_1 = 1 ≤ a_1 = 1
d_2 = 4 ≤ a_2 = 4
d_3 = 1 ≤ a_3 = 1
d_4 = 1 ≤ a_4 = 1 | instruction | 0 | 74,206 | 13 | 148,412 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
def in_arr():
return map(int,raw_input().split())
def pr_num(n):
stdout.write(str(n)+'\n')
def pr_arr(arr):
for i in arr:
stdout.write(str(i)+' ')
stdout.write('\n')
range = xrange # not for python 3.0+
n=int(raw_input())
l=in_arr()
ans=[]
arr=[]
one=[]
sm=0
for i in range(n):
if l[i]==1:
one.append(i+1)
else:
arr.append([i+1,l[i]])
sm+=l[i]
n1=len(one)
if sm-(2*(len(arr)-1))<n1:
pr('NO')
exit()
for i in range(1,len(arr)):
ans.append((arr[i-1][0],arr[i][0]))
arr[i][1]-=1
arr[i-1][1]-=1
if one:
ans.append((one.pop(),arr[0][0]))
arr[0][1]-=1
if one:
ans.append((one.pop(),arr[-1][0]))
arr[-1][1]-=1
for i in range(len(arr)):
while one and arr[i][1]:
ans.append((one.pop(),arr[i][0]))
arr[i][1]-=1
pr('YES '+str(len(arr)-1+min(2,n1))+'\n')
pr_num(len(ans))
for i in ans:
pr_arr(i)
``` | output | 1 | 74,206 | 13 | 148,413 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Graph constructive problems are back! This time the graph you are asked to build should match the following properties.
The graph is connected if and only if there exists a path between every pair of vertices.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
The degree of a vertex is the number of edges incident to it.
Given a sequence of n integers a_1, a_2, ..., a_n construct a connected undirected graph of n vertices such that:
* the graph contains no self-loops and no multiple edges;
* the degree d_i of the i-th vertex doesn't exceed a_i (i.e. d_i ≤ a_i);
* the diameter of the graph is maximum possible.
Output the resulting graph or report that no solution exists.
Input
The first line contains a single integer n (3 ≤ n ≤ 500) — the number of vertices in the graph.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n - 1) — the upper limits to vertex degrees.
Output
Print "NO" if no graph can be constructed under the given conditions.
Otherwise print "YES" and the diameter of the resulting graph in the first line.
The second line should contain a single integer m — the number of edges in the resulting graph.
The i-th of the next m lines should contain two integers v_i, u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the description of the i-th edge. The graph should contain no multiple edges — for each pair (x, y) you output, you should output no more pairs (x, y) or (y, x).
Examples
Input
3
2 2 2
Output
YES 2
2
1 2
2 3
Input
5
1 4 1 1 1
Output
YES 2
4
1 2
3 2
4 2
5 2
Input
3
1 1 1
Output
NO
Note
Here are the graphs for the first two example cases. Both have diameter of 2.
<image> d_1 = 1 ≤ a_1 = 2
d_2 = 2 ≤ a_2 = 2
d_3 = 1 ≤ a_3 = 2
<image> d_1 = 1 ≤ a_1 = 1
d_2 = 4 ≤ a_2 = 4
d_3 = 1 ≤ a_3 = 1
d_4 = 1 ≤ a_4 = 1
Submitted Solution:
```
n = int(input())
o, t, m = [], [], []
for i, e in enumerate(map(int, input().split())):
if e == 1:
o.append(i)
else:
m.append([e, i])
if len(m) == 0:
print("NO")
exit()
m.sort()
edges = []
res = len(m) - 1
for i in range(len(m) - 1):
edges.append(f'{m[i][1] + 1} {m[i + 1][1] + 1}')
m[i][0] -= 1
m[i + 1][0] -= 1
def f(i):
edges.append(f'{m[i][1] + 1} {o.pop() + 1}')
m[i][0] -= 1
if len(o) >= 1:
f(0)
res += 1
if len(o) >= 1:
f(-1)
res += 1
if len(o) >= 1:
i = 0
while len(o) and i < len(m):
if m[i][0] > 0:
f(i)
else:
i += 1
if len(o) != 0:
print("NO")
else:
print("YES", res)
print(len(edges))
print('\n'.join(edges))
``` | instruction | 0 | 74,207 | 13 | 148,414 |
Yes | output | 1 | 74,207 | 13 | 148,415 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Graph constructive problems are back! This time the graph you are asked to build should match the following properties.
The graph is connected if and only if there exists a path between every pair of vertices.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
The degree of a vertex is the number of edges incident to it.
Given a sequence of n integers a_1, a_2, ..., a_n construct a connected undirected graph of n vertices such that:
* the graph contains no self-loops and no multiple edges;
* the degree d_i of the i-th vertex doesn't exceed a_i (i.e. d_i ≤ a_i);
* the diameter of the graph is maximum possible.
Output the resulting graph or report that no solution exists.
Input
The first line contains a single integer n (3 ≤ n ≤ 500) — the number of vertices in the graph.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n - 1) — the upper limits to vertex degrees.
Output
Print "NO" if no graph can be constructed under the given conditions.
Otherwise print "YES" and the diameter of the resulting graph in the first line.
The second line should contain a single integer m — the number of edges in the resulting graph.
The i-th of the next m lines should contain two integers v_i, u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the description of the i-th edge. The graph should contain no multiple edges — for each pair (x, y) you output, you should output no more pairs (x, y) or (y, x).
Examples
Input
3
2 2 2
Output
YES 2
2
1 2
2 3
Input
5
1 4 1 1 1
Output
YES 2
4
1 2
3 2
4 2
5 2
Input
3
1 1 1
Output
NO
Note
Here are the graphs for the first two example cases. Both have diameter of 2.
<image> d_1 = 1 ≤ a_1 = 2
d_2 = 2 ≤ a_2 = 2
d_3 = 1 ≤ a_3 = 2
<image> d_1 = 1 ≤ a_1 = 1
d_2 = 4 ≤ a_2 = 4
d_3 = 1 ≤ a_3 = 1
d_4 = 1 ≤ a_4 = 1
Submitted Solution:
```
a = []
n = 0
Ones = []
def solution ():
s = 0
for item in a :
s = s + item
if s < 2*(n-1) :
print("NO")
return
for i in range(n):
if a[i] == 1 :
a[i] = 0
Ones.append(i)
t = len(Ones)
d = (n-t) - 1 + min(2,t)
print("YES " + str(d) + "\n" + str(n-1) )
l = -1
if len(Ones) != 0 :
l = Ones[len(Ones)-1]
Ones.remove(l)
for i in range (n):
if a[i] > 1 :
if l !=-1:
a[l] = a[l] -1
a[i] = a[i] -1
print (str (l+1) + " " + str(i+1))
l=i
i = n-1
while i >=0 :
while len(Ones) > 0 and a[i] > 0 :
a[i] = a[i] -1
u = Ones[len(Ones)-1]
print(str(i+1) + " " + str (u +1) )
Ones.remove(u)
i = i -1
if __name__ == "__main__":
line = int(input())
n = int(line)
line = str(input()).split()
for i in range (n):
a.append(int(line[i]))
solution()
``` | instruction | 0 | 74,208 | 13 | 148,416 |
Yes | output | 1 | 74,208 | 13 | 148,417 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Graph constructive problems are back! This time the graph you are asked to build should match the following properties.
The graph is connected if and only if there exists a path between every pair of vertices.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
The degree of a vertex is the number of edges incident to it.
Given a sequence of n integers a_1, a_2, ..., a_n construct a connected undirected graph of n vertices such that:
* the graph contains no self-loops and no multiple edges;
* the degree d_i of the i-th vertex doesn't exceed a_i (i.e. d_i ≤ a_i);
* the diameter of the graph is maximum possible.
Output the resulting graph or report that no solution exists.
Input
The first line contains a single integer n (3 ≤ n ≤ 500) — the number of vertices in the graph.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n - 1) — the upper limits to vertex degrees.
Output
Print "NO" if no graph can be constructed under the given conditions.
Otherwise print "YES" and the diameter of the resulting graph in the first line.
The second line should contain a single integer m — the number of edges in the resulting graph.
The i-th of the next m lines should contain two integers v_i, u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the description of the i-th edge. The graph should contain no multiple edges — for each pair (x, y) you output, you should output no more pairs (x, y) or (y, x).
Examples
Input
3
2 2 2
Output
YES 2
2
1 2
2 3
Input
5
1 4 1 1 1
Output
YES 2
4
1 2
3 2
4 2
5 2
Input
3
1 1 1
Output
NO
Note
Here are the graphs for the first two example cases. Both have diameter of 2.
<image> d_1 = 1 ≤ a_1 = 2
d_2 = 2 ≤ a_2 = 2
d_3 = 1 ≤ a_3 = 2
<image> d_1 = 1 ≤ a_1 = 1
d_2 = 4 ≤ a_2 = 4
d_3 = 1 ≤ a_3 = 1
d_4 = 1 ≤ a_4 = 1
Submitted Solution:
```
def main():
n = int(input())
a = list(map(int, input().split()))
if sum(a) < 2 * n - 2:
print("NO"); return
Mx0 = 0
for i in range(n):
if a[i] < a[Mx0]:
Mx0 = i
Mx1 = 0 if Mx0 else 1
for i in range(n):
if i == Mx0:
continue
if a[i] < a[Mx1]:
Mx1 = i
ones = []; non_ones = []
for i in range(n):
if i == Mx0 or i == Mx1:
continue
if a[i] == 1:
ones.append(i)
else:
non_ones.append(i)
a[i] -= 2
print("YES", len(non_ones) + 2 - 1)
print(n - 1)
print(Mx0 + 1, non_ones[0] + 1)
for i in range(len(non_ones) - 1):
print(non_ones[i] + 1, non_ones[i + 1] + 1)
print(non_ones[-1] + 1, Mx1 + 1)
z = 0
for i in range(len(ones)):
while not a[non_ones[z]]:
z += 1
a[non_ones[z]] -= 1
print(ones[i] + 1, non_ones[z] + 1)
main()
``` | instruction | 0 | 74,209 | 13 | 148,418 |
Yes | output | 1 | 74,209 | 13 | 148,419 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Graph constructive problems are back! This time the graph you are asked to build should match the following properties.
The graph is connected if and only if there exists a path between every pair of vertices.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
The degree of a vertex is the number of edges incident to it.
Given a sequence of n integers a_1, a_2, ..., a_n construct a connected undirected graph of n vertices such that:
* the graph contains no self-loops and no multiple edges;
* the degree d_i of the i-th vertex doesn't exceed a_i (i.e. d_i ≤ a_i);
* the diameter of the graph is maximum possible.
Output the resulting graph or report that no solution exists.
Input
The first line contains a single integer n (3 ≤ n ≤ 500) — the number of vertices in the graph.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n - 1) — the upper limits to vertex degrees.
Output
Print "NO" if no graph can be constructed under the given conditions.
Otherwise print "YES" and the diameter of the resulting graph in the first line.
The second line should contain a single integer m — the number of edges in the resulting graph.
The i-th of the next m lines should contain two integers v_i, u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the description of the i-th edge. The graph should contain no multiple edges — for each pair (x, y) you output, you should output no more pairs (x, y) or (y, x).
Examples
Input
3
2 2 2
Output
YES 2
2
1 2
2 3
Input
5
1 4 1 1 1
Output
YES 2
4
1 2
3 2
4 2
5 2
Input
3
1 1 1
Output
NO
Note
Here are the graphs for the first two example cases. Both have diameter of 2.
<image> d_1 = 1 ≤ a_1 = 2
d_2 = 2 ≤ a_2 = 2
d_3 = 1 ≤ a_3 = 2
<image> d_1 = 1 ≤ a_1 = 1
d_2 = 4 ≤ a_2 = 4
d_3 = 1 ≤ a_3 = 1
d_4 = 1 ≤ a_4 = 1
Submitted Solution:
```
n = int(input())
a = [0]
sum = 0
for i in map(int, input().split()) :
a.append(i)
sum += i
last = 0
ans = 0
edge = []
for i in range(1, n + 1, 1) :
if(a[i] == 1) :
last = i
a[last] = 0
for i in range(1, n + 1, 1) :
if(a[i] > 1) :
if(last) :
edge.append([last, i])
ans += 1
last = i
for i in range(1, n + 1, 1) :
if(a[i] == 1 and last) :
edge.append([last, i])
last = 0
a[i] = 0
ans += 1
for i in range(1, n + 1, 1) :
for j in range(1, n + 1, 1) :
if(a[j] == 1 and a[i] > 2) :
edge.append([i, j])
a[i] -= 1
a[j] -= 1
if(len(edge) != n - 1) :
print("NO")
else :
print("YES", ans)
print(len(edge))
for i in edge :
print(i[0], i[1])
``` | instruction | 0 | 74,210 | 13 | 148,420 |
Yes | output | 1 | 74,210 | 13 | 148,421 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.