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.
After Vitaly was expelled from the university, he became interested in the graph theory.
Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once.
Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t β the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w β the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges.
Two ways to add edges to the graph are considered equal if they have the same sets of added edges.
Since Vitaly does not study at the university, he asked you to help him with this task.
Input
The first line of the input contains two integers n and m (<image> β the number of vertices in the graph and the number of edges in the graph.
Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers ai, bi (1 β€ ai, bi β€ n) β the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space.
It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected.
Output
Print in the first line of the output two space-separated integers t and w β the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this.
Examples
Input
4 4
1 2
1 3
4 2
4 3
Output
1 2
Input
3 3
1 2
2 3
3 1
Output
0 1
Input
3 0
Output
3 1
Note
The simple cycle is a cycle that doesn't contain any vertex twice.
Submitted Solution:
```
import sys
import threading
sys.setrecursionlimit(100500)
def nc2(k):
return k * (k - 1) // 2
def solve():
def dfs(u):
comp[u] = n_comp
for v in g[u]:
if color[v] == 0:
color[v] = 3 - color[u]
dfs(v)
elif color[u] == color[v]:
bad_graph = True
n, m = map(int, input().split())
g = dict()
for i in range(1, n + 1):
g[i] = set()
for i in range(m):
a, b = map(int, input().split())
g[a].add(b)
g[b].add(a)
bad_graph = False
color = [0] * (n + 1)
comp = [0] * (n + 1)
n_comp = 0
for u in range(1, n + 1):
if color[u] == 0:
n_comp += 1
color[u] = 1
dfs(u)
if bad_graph:
print(0, 1)
else:
counts = [0] * (n_comp + 1)
counts_1 = [0] * (n_comp + 1)
counts_2 = [0] * (n_comp + 1)
for i in range(1, n + 1):
counts[comp[i]] += 1
if color[i] == 1:
counts_1[comp[i]] += 1
else:
counts_2[comp[i]] += 1
c = max(counts)
if c == 1:
print(3, n * (n - 1) * (n - 2) // 6)
elif c == 2:
print(2, counts.count(2) * (n - 2))
elif c >= 3:
ans = 0
for i in range(1, n_comp + 1):
if counts[i] >= 3:
ans += nc2(counts_1[i]) + nc2(counts_2[i])
print(1, ans)
thread = threading.Thread(target=solve)
thread.start()
``` | instruction | 0 | 93,923 | 13 | 187,846 |
No | output | 1 | 93,923 | 13 | 187,847 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After Vitaly was expelled from the university, he became interested in the graph theory.
Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once.
Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t β the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w β the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges.
Two ways to add edges to the graph are considered equal if they have the same sets of added edges.
Since Vitaly does not study at the university, he asked you to help him with this task.
Input
The first line of the input contains two integers n and m (<image> β the number of vertices in the graph and the number of edges in the graph.
Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers ai, bi (1 β€ ai, bi β€ n) β the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space.
It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected.
Output
Print in the first line of the output two space-separated integers t and w β the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this.
Examples
Input
4 4
1 2
1 3
4 2
4 3
Output
1 2
Input
3 3
1 2
2 3
3 1
Output
0 1
Input
3 0
Output
3 1
Note
The simple cycle is a cycle that doesn't contain any vertex twice.
Submitted Solution:
```
__author__ = 'Andrey'
import sys
import threading
threading.stack_size(67108864)
sys.setrecursionlimit(10 ** 6)
def nc2(k):
return k * (k - 1) // 2
def dfs(u, n_comp, color, bad_graph, comp, g):
comp[u] = n_comp
for v in g[u]:
if color[v] == 0:
color[v] = 3 - color[u]
dfs(v, n_comp, color, bad_graph, comp, g)
elif color[u] == color[v]:
bad_graph = True
return comp, color, bad_graph
def solve():
# f = open("bipartite.in")
# n, m = map(int, f.readline().rstrip().split())
n, m = map(int, input().split())
g = dict()
for i in range(1, n + 1):
g[i] = set()
for i in range(m):
# a, b = map(int, f.readline().rstrip().split())
a, b = map(int, input().split())
g[a].add(b)
g[b].add(a)
bad_graph = False
color = [0] * (n + 1)
comp = [0] * (n + 1)
n_comp = 0
for u in range(1, n + 1):
if color[u] == 0:
n_comp += 1
color[u] = 1
comp, color, bad_graph = dfs(u, n_comp, color, bad_graph, comp, g)
if bad_graph:
print(0, 1)
else:
counts = [0] * (n_comp + 1)
counts_1 = [0] * (n_comp + 1)
counts_2 = [0] * (n_comp + 1)
for i in range(1, n + 1):
counts[comp[i]] += 1
if color[i] == 1:
counts_1[comp[i]] += 1
else:
counts_2[comp[i]] += 1
c = max(counts)
if c == 1:
print(3, n * (n - 1) * (n - 2) // 6)
elif c == 2:
print(2, counts.count(2) * (n - 2))
elif c >= 3:
ans = 0
for i in range(1, n_comp + 1):
if counts[i] >= 3:
ans += nc2(counts_1[i]) + nc2(counts_2[i])
print(1, ans)
thread = threading.Thread(target=solve)
thread.start()
``` | instruction | 0 | 93,924 | 13 | 187,848 |
No | output | 1 | 93,924 | 13 | 187,849 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph β something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) β the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 β€ aj β€ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 β€ uj, vj β€ n, uj β vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1 | instruction | 0 | 93,941 | 13 | 187,882 |
Tags: constructive algorithms, data structures, graphs
Correct Solution:
```
f = lambda: map(int, input().split())
n, m = f()
p = []
for i in range(m):
a, b = f()
p.append((a, 1 - b, i))
p.sort()
k = j = 0
s = [0] * m
u, v = 1, 3
for a, b, i in p:
if not b:
k += j
s[i] = (j + 1, j + 2)
j += 1
elif k:
k -= 1
s[i] = (u, v)
if v - u - 2: u += 1
else: u, v = 1, v + 1
else:
print(-1)
exit(0)
for x, y in s: print(x, y)
``` | output | 1 | 93,941 | 13 | 187,883 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph β something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) β the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 β€ aj β€ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 β€ uj, vj β€ n, uj β vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1 | instruction | 0 | 93,942 | 13 | 187,884 |
Tags: constructive algorithms, data structures, graphs
Correct Solution:
```
import sys
from operator import itemgetter
lines = sys.stdin.readlines()
n, m = map(int, lines[0].split(' '))
def build_edge(i, row):
parts = row.split(' ')
return (int(parts[0]), int(parts[1]), i)
def edge_key(a):
return (a[0], -a[1])
edges = [build_edge(i, row) for i, row in enumerate(lines[1:])]
edges = sorted(edges, key=edge_key)
x, y = 1, 2
vertex = 1
color = [0 for x in range(n)]
color[0] = 1 # root of tree
ans = []
for weight, used, index in edges:
if used == 1:
color[vertex] = 1
ans.append((0, vertex, index))
vertex += 1
else:
if color[x] != 1 or color[y] != 1:
print(-1)
exit(0)
ans.append((x,y,index))
x += 1
if x == y:
x = 1
y += 1
ans = sorted(ans, key=itemgetter(2))
for edge in ans:
print("%s %s" % (edge[0]+1, edge[1]+1))
``` | output | 1 | 93,942 | 13 | 187,885 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph β something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) β the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 β€ aj β€ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 β€ uj, vj β€ n, uj β vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1 | instruction | 0 | 93,943 | 13 | 187,886 |
Tags: constructive algorithms, data structures, graphs
Correct Solution:
```
def read_data():
n, m = map(int, input().split())
ABs = []
for i in range(m):
a, b = map(int, input().split())
ABs.append((a, b))
return n, m, ABs
def solve(n, m, ABs):
edges = [(a, -b, i) for i, (a, b) in enumerate(ABs)]
edges.sort()
ans = [(0, 0) for i in range(m)]
v = 0
count = 0
s = 1
t = 2
for a, mb, i in edges:
count += 1
if mb == -1:
v += 1
ans[i] = (0, v)
else:
if t > v:
return False, []
ans[i] = (s, t)
if t == s + 1:
s = 1
t += 1
else:
s += 1
return True, ans
n, m, ABs = read_data()
res, ans = solve(n, m, ABs)
if res:
for i, j in ans:
print(i + 1, j + 1)
else:
print(-1)
``` | output | 1 | 93,943 | 13 | 187,887 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph β something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) β the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 β€ aj β€ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 β€ uj, vj β€ n, uj β vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1 | instruction | 0 | 93,944 | 13 | 187,888 |
Tags: constructive algorithms, data structures, graphs
Correct Solution:
```
readInts=lambda: list(map(int, input().split()))
n,m=readInts()
edge=[]
for _ in range(m):
l,f=readInts()
if f==1:
f=-1
edge+=[(l,f,_)]
edge.sort()
ok=True
cnt=0;ret=[(0,0)]*m
u=2;v=3;t=2
for e in edge:
if e[1]==-1:
ret[e[2]]=(1,t)
cnt+=t-2
t+=1
elif cnt<=0:
ok=False
break
else:
ret[e[2]]=(u,v)
cnt-=1
u+=1
if u==v:
u=2
v+=1
if ok==False:
print(-1)
else:
for e in ret:
print(*e)
``` | output | 1 | 93,944 | 13 | 187,889 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph β something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) β the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 β€ aj β€ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 β€ uj, vj β€ n, uj β vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1 | instruction | 0 | 93,945 | 13 | 187,890 |
Tags: constructive algorithms, data structures, graphs
Correct Solution:
```
def graph(e):
e = [(w, i, b) for i, (w, b) in enumerate(e)]
e.sort()
g = [None]*len(e)
mst = [(w, i) for w, i, b in e if b]
for n, (w, i) in enumerate(mst, 2):
g[i] = 1, n
cm = 0
available = []
for w, i, b in e:
if not b:
if not available:
cm += 1
if mst[cm][0] > w:
return None
available = [(u, cm+2) for u in range(2, cm+2)]
g[i] = available.pop()
return g
if __name__ == '__main__':
n, m = map(int, input().split())
e = []
for _ in range(m):
a, b = map(int, input().split())
e.append((a, b))
g = graph(e)
if g:
for u, v in g:
print("{} {}".format(u, v))
else:
print(-1)
``` | output | 1 | 93,945 | 13 | 187,891 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph β something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) β the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 β€ aj β€ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 β€ uj, vj β€ n, uj β vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1 | instruction | 0 | 93,946 | 13 | 187,892 |
Tags: constructive algorithms, data structures, graphs
Correct Solution:
```
def main():
n, m = map(int, input().split())
tmp = ([], [])
for i in range(m):
a, b = input().split()
tmp[b == "1"].append((int(a), i))
for l in tmp:
l.sort()
additional, spanning = tmp
tmp = []
def concurrent_way():
for y, (ww, _) in enumerate(spanning, 2):
for x in range(2, y):
yield ww, x, y
for (w, e), (wmax, v1, v2) in zip(additional, concurrent_way()):
if w < wmax:
print("-1")
return
else:
tmp.append((e, v1, v2))
tmp.extend((n, 1, v) for v, (_, n) in enumerate(spanning, 2))
tmp.sort()
f = " ".join
print('\n'.join(f((str(j), str(k))) for _, j, k in tmp))
if __name__ == '__main__':
main()
``` | output | 1 | 93,946 | 13 | 187,893 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph β something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) β the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 β€ aj β€ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 β€ uj, vj β€ n, uj β vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1 | instruction | 0 | 93,947 | 13 | 187,894 |
Tags: constructive algorithms, data structures, graphs
Correct Solution:
```
def parse(i):
t = input().split()
return int(t[0]), int(t[1]), i
n, m = [int(x) for x in input().split()]
list = [parse(i) for i in range(m)]
list.sort(key=lambda x: (x[0], -x[1]))
# print(list)
f = 0
t = 1
fakeFrom = 1
fakeTo = 2
graph = []
for i in range(m):
if list[i][1] == 1:
graph.append((f + 1, t + 1, list[i][2]))
t += 1
else:
graph.append((fakeFrom + 1, fakeTo + 1, list[i][2]))
if fakeTo >= t:
print(-1)
exit(0)
fakeFrom += 1
if fakeFrom == fakeTo:
fakeFrom = 1
fakeTo += 1
# if fakeTo >= t:
# print(-1)
# exit(0)
# print(graph)
graph.sort(key=lambda x: x[2])
for x in graph:
print(x[0], x[1])
``` | output | 1 | 93,947 | 13 | 187,895 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph β something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) β the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 β€ aj β€ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 β€ uj, vj β€ n, uj β vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1 | instruction | 0 | 93,948 | 13 | 187,896 |
Tags: constructive algorithms, data structures, graphs
Correct Solution:
```
f = lambda: map(int, input().split())
n, m = f()
p = []
for i in range(m):
a, b = f()
p.append((a, 1 - b, i))
p.sort()
k = j = 0
s = [0] * m
u, v = 1, 3
for a, b, i in p:
if not b:
k += j
s[i] = (j + 1, j + 2)
j += 1
elif k:
k -= 1
s[i] = (u, v)
if v - u - 2: u += 1
else: u, v = 1, v + 1
else:
print(-1)
exit(0)
for x, y in s: print(x, y)
# Made By Mostafa_Khaled
``` | output | 1 | 93,948 | 13 | 187,897 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph β something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) β the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 β€ aj β€ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 β€ uj, vj β€ n, uj β vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1
Submitted Solution:
```
n,m = map(int,input().split())
a = []
for i in range(m):
x,y = map(int,input().split())
a.append((x,y,i))
a.sort()
b,c,d = [object()]*m,2,[0]*(n+1)
for i in range(m):
if a[i][1]:
b[i]=(a[i][2],1,c)
d[c]=a[i][0]
c+=1
x,y,f = 2,3,0
for i in range(m):
if not a[i][1]:
if d[x]<= a[i][0] and d[y]<=a[i][0]:
b[i]=(a[i][2],x,y)
else:
f=1
break
x+=1
if x==y:
x=2
y+=1
if f:
print('-1')
else:
b.sort()
for _,i,j in b:
print(i,j)
``` | instruction | 0 | 93,949 | 13 | 187,898 |
Yes | output | 1 | 93,949 | 13 | 187,899 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph β something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) β the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 β€ aj β€ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 β€ uj, vj β€ n, uj β vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1
Submitted Solution:
```
__author__ = 'MoonBall'
import sys
import functools
# sys.stdin = open('data/D.in', 'r')
T = 1
def process():
N, M = list(map(int, input().split()))
e = []
for _ in range(M): e.append(list(map(int, input().split())) + [_])
e = sorted(e, key=functools.cmp_to_key(lambda x, y: y[1] - x[1] if x[0] == y[0] else x[0] - y[0]))
ans = [0] * M
# print(e)
i = 3
j = 1
has = 1
ok = True
for _e in e:
if _e[1] == 1:
has = has + 1
ans[_e[2]] = (has, has - 1)
else:
if has < i:
ok = False
else:
ans[_e[2]] = (i, j)
if j == i - 2:
i = i + 1
j = 1
else:
j = j + 1
if not ok:
print(-1)
else:
for u, v in ans: print(u, v)
for _ in range(T):
process()
``` | instruction | 0 | 93,950 | 13 | 187,900 |
Yes | output | 1 | 93,950 | 13 | 187,901 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph β something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) β the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 β€ aj β€ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 β€ uj, vj β€ n, uj β vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1
Submitted Solution:
```
import sys
from math import gcd,sqrt,ceil,log2
from collections import defaultdict,Counter,deque
from bisect import bisect_left,bisect_right
import math
sys.setrecursionlimit(2*10**5+10)
import heapq
from itertools import permutations
# input=sys.stdin.readline
# def print(x):
# sys.stdout.write(str(x)+"\n")
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
aa='abcdefghijklmnopqrstuvwxyz'
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# import sys
# import io, os
# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def get_sum(bit,i):
s = 0
i+=1
while i>0:
s+=bit[i]
i-=i&(-i)
return s
def update(bit,n,i,v):
i+=1
while i<=n:
bit[i]+=v
i+=i&(-i)
def modInverse(b,m):
g = math.gcd(b, m)
if (g != 1):
return -1
else:
return pow(b, m - 2, m)
def primeFactors(n):
sa = []
# sa.add(n)
while n % 2 == 0:
sa.append(2)
n = n // 2
for i in range(3,int(math.sqrt(n))+1,2):
while n % i== 0:
sa.append(i)
n = n // i
# sa.add(n)
if n > 2:
sa.append(n)
return sa
def seive(n):
pri = [True]*(n+1)
p = 2
while p*p<=n:
if pri[p] == True:
for i in range(p*p,n+1,p):
pri[i] = False
p+=1
return pri
def check_prim(n):
if n<0:
return False
for i in range(2,int(sqrt(n))+1):
if n%i == 0:
return False
return True
def getZarr(string, z):
n = len(string)
# [L,R] make a window which matches
# with prefix of s
l, r, k = 0, 0, 0
for i in range(1, n):
# if i>R nothing matches so we will calculate.
# Z[i] using naive way.
if i > r:
l, r = i, i
# R-L = 0 in starting, so it will start
# checking from 0'th index. For example,
# for "ababab" and i = 1, the value of R
# remains 0 and Z[i] becomes 0. For string
# "aaaaaa" and i = 1, Z[i] and R become 5
while r < n and string[r - l] == string[r]:
r += 1
z[i] = r - l
r -= 1
else:
# k = i-L so k corresponds to number which
# matches in [L,R] interval.
k = i - l
# if Z[k] is less than remaining interval
# then Z[i] will be equal to Z[k].
# For example, str = "ababab", i = 3, R = 5
# and L = 2
if z[k] < r - i + 1:
z[i] = z[k]
# For example str = "aaaaaa" and i = 2,
# R is 5, L is 0
else:
# else start from R and check manually
l = i
while r < n and string[r - l] == string[r]:
r += 1
z[i] = r - l
r -= 1
def search(text, pattern):
# Create concatenated string "P$T"
concat = pattern + "$" + text
l = len(concat)
z = [0] * l
getZarr(concat, z)
ha = []
for i in range(l):
if z[i] == len(pattern):
ha.append(i - len(pattern) - 1)
return ha
# n,k = map(int,input().split())
# l = list(map(int,input().split()))
#
# n = int(input())
# l = list(map(int,input().split()))
#
# hash = defaultdict(list)
# la = []
#
# for i in range(n):
# la.append([l[i],i+1])
#
# la.sort(key = lambda x: (x[0],-x[1]))
# ans = []
# r = n
# flag = 0
# lo = []
# ha = [i for i in range(n,0,-1)]
# yo = []
# for a,b in la:
#
# if a == 1:
# ans.append([r,b])
# # hash[(1,1)].append([b,r])
# lo.append((r,b))
# ha.pop(0)
# yo.append([r,b])
# r-=1
#
# elif a == 2:
# # print(yo,lo)
# # print(hash[1,1])
# if lo == []:
# flag = 1
# break
# c,d = lo.pop(0)
# yo.pop(0)
# if b>=d:
# flag = 1
# break
# ans.append([c,b])
# yo.append([c,b])
#
#
#
# elif a == 3:
#
# if yo == []:
# flag = 1
# break
# c,d = yo.pop(0)
# if b>=d:
# flag = 1
# break
# if ha == []:
# flag = 1
# break
#
# ka = ha.pop(0)
#
# ans.append([ka,b])
# ans.append([ka,d])
# yo.append([ka,b])
#
# if flag:
# print(-1)
# else:
# print(len(ans))
# for a,b in ans:
# print(a,b)
def mergeIntervals(arr):
# Sorting based on the increasing order
# of the start intervals
arr.sort(key = lambda x: x[0])
# array to hold the merged intervals
m = []
s = -10000
max = -100000
for i in range(len(arr)):
a = arr[i]
if a[0] > max:
if i != 0:
m.append([s,max])
max = a[1]
s = a[0]
else:
if a[1] >= max:
max = a[1]
#'max' value gives the last point of
# that particular interval
# 's' gives the starting point of that interval
# 'm' array contains the list of all merged intervals
if max != -100000 and [s, max] not in m:
m.append([s, max])
return m
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
def ncr(n, r, p):
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den,
p - 2, p)) % p
def sol(n):
seti = set()
for i in range(1,int(sqrt(n))+1):
if n%i == 0:
seti.add(n//i)
seti.add(i)
return seti
def lcm(a,b):
return (a*b)//gcd(a,b)
#
# n,p = map(int,input().split())
#
# s = input()
#
# if n <=2:
# if n == 1:
# pass
# if n == 2:
# pass
# i = n-1
# idx = -1
# while i>=0:
# z = ord(s[i])-96
# k = chr(z+1+96)
# flag = 1
# if i-1>=0:
# if s[i-1]!=k:
# flag+=1
# else:
# flag+=1
# if i-2>=0:
# if s[i-2]!=k:
# flag+=1
# else:
# flag+=1
# if flag == 2:
# idx = i
# s[i] = k
# break
# if idx == -1:
# print('NO')
# exit()
# for i in range(idx+1,n):
# if
#
def moore_voting(l):
count1 = 0
count2 = 0
first = 10**18
second = 10**18
n = len(l)
for i in range(n):
if l[i] == first:
count1+=1
elif l[i] == second:
count2+=1
elif count1 == 0:
count1+=1
first = l[i]
elif count2 == 0:
count2+=1
second = l[i]
else:
count1-=1
count2-=1
for i in range(n):
if l[i] == first:
count1+=1
elif l[i] == second:
count2+=1
if count1>n//3:
return first
if count2>n//3:
return second
return -1
def find_parent(u,parent):
if u!=parent[u]:
parent[u] = find_parent(parent[u],parent)
return parent[u]
def dis_union(n):
par = [i for i in range(n+1)]
rank = [1]*(n+1)
k = int(input())
for i in range(k):
a,b = map(int,input().split())
z1,z2 = find_parent(a,par),find_parent(b,par)
if z1!=z2:
par[z1] = z2
rank[z2]+=rank[z1]
def dijkstra(n,tot,hash):
hea = [[0,n]]
dis = [10**18]*(tot+1)
dis[n] = 0
boo = defaultdict(bool)
check = defaultdict(int)
while hea:
a,b = heapq.heappop(hea)
if boo[b]:
continue
boo[b] = True
for i,w in hash[b]:
if b == 1:
c = 0
if (1,i,w) in nodes:
c = nodes[(1,i,w)]
del nodes[(1,i,w)]
if dis[b]+w<dis[i]:
dis[i] = dis[b]+w
check[i] = c
elif dis[b]+w == dis[i] and c == 0:
dis[i] = dis[b]+w
check[i] = c
else:
if dis[b]+w<=dis[i]:
dis[i] = dis[b]+w
check[i] = check[b]
heapq.heappush(hea,[dis[i],i])
return check
def power(x,y,p):
res = 1
x = x%p
if x == 0:
return 0
while y>0:
if (y&1) == 1:
res*=x
x = x*x
y = y>>1
return res
#
# n,m = map(int,input().split())
# hash = defaultdict(list)
# ans = set()
# cur = 2
# rest = []
# now = []
# ba = []
# ho = defaultdict(bool)
# for i in range(m):
# a,b = map(int,input().split())
# ba.append(a)
# if b == 1:
# ans.add((a,1,cur))
# now.append([a,1,cur])
# ho[(1,cur)] = True
# ho[(cur,1)] = True
# cur+=1
#
#
# else:
# rest.append(a)
# ha = n-1
#
#
# rest.sort()
# # print(now)
# inf = -10**18
# i = 0
# cur = 2
# while ha!=m:
# if rest == []:
# break
# yo = cur+1
# while yo<=n:
#
# x1,x2 =
#
#
#
# hash = defaultdict(list)
#
# for a,b,c in ans:
# hash[a].append((b,c))
# yo = []
# for a in ba:
# while hash[a]!=[]:
# c,d = hash[a].pop(0)
# yo.append((c,d))
#
# for a,b in yo:
# print(a,b)
n,m = map(int,input().split())
ans = set()
cur = 2
rest = []
now = []
ba = []
hash = defaultdict(int)
for i in range(m):
a,b = map(int,input().split())
now.append([a,b,i])
now.sort()
yo = [[0,0]]*(m)
for i in range(m):
a,b,x = now[i]
ba.append([x,a])
if b == 1:
hash[(1,cur)] = a
yo[x] = [1,cur]
cur+=1
else:
rest.append(a)
rest.sort()
ba.sort()
ha = n-1
to = 2
fro = 3
while ha!=m:
z = rest.pop(0)
a,b = to,fro
z1,z2 = hash[(1,to)],hash[(1,fro)]
if z<z1 or z<z2:
# print(z,a,b,z1,z2)
print(-1)
exit()
ans.add((z,a,b))
if rest == []:
break
to+=1
if to == fro:
fro+=1
to = 2
hash = defaultdict(list)
for a,b,c in ans:
hash[a].append((b,c))
# print(hash)
# print(ba)
for x,a in ba:
if yo[x] == [0,0]:
c,d = hash[a].pop(0)
yo[x] = c,d
for a,b in yo:
print(a,b)
``` | instruction | 0 | 93,951 | 13 | 187,902 |
Yes | output | 1 | 93,951 | 13 | 187,903 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph β something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) β the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 β€ aj β€ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 β€ uj, vj β€ n, uj β vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1
Submitted Solution:
```
n, m = map(int, input().split())
arr = []
for i in range(m):
a, b = map(int, input().split())
arr.append([a, -b, i + 1])
arr.sort()
ans = [[-1,-1] for i in range(m)]
ok = True
at = 2
last = 3
curr = 2
for i in range(m):
idx = arr[i][2] - 1
inc = arr[i][1]
if(inc):
ans[idx] = [1, curr]
curr += 1
else:
if(last < curr):
ans[idx] = [at, last]
at += 1
if(at == last):
last += 1
at = 2
else:
ok= False
# print(arr)
if(ok):
for i in ans:
print(*i)
else:
print(-1)
# print(*ans)
``` | instruction | 0 | 93,952 | 13 | 187,904 |
Yes | output | 1 | 93,952 | 13 | 187,905 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph β something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) β the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 β€ aj β€ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 β€ uj, vj β€ n, uj β vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1
Submitted Solution:
```
n,m = map(int,input().split())
a = []
for i in range(m):
x,y = map(int,input().split())
a.append((x,y,i))
a.sort()
b,c,d = [object()]*m,2,[0]*(n+1)
for i in range(m):
if a[i][1]:
b[i]=(a[i][2],1,c)
d[c]=a[i][0]
c+=1
x,y,f = 2,3,0
for i in range(m):
if not a[i][1]:
if d[x]<= a[i][0] and d[y]<=a[i][0]:
b[i]=(a[i][2],x,y)
else:
f=1
break
y+=1
if y>n:
x+=1
y=x+1
if f:
print('-1')
else:
b.sort()
for _,i,j in b:
print(i,j)
``` | instruction | 0 | 93,953 | 13 | 187,906 |
No | output | 1 | 93,953 | 13 | 187,907 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph β something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) β the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 β€ aj β€ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 β€ uj, vj β€ n, uj β vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1
Submitted Solution:
```
n,m = map(int, input().split())
l = []
for i in range(m):
a,b = map(int, input().split())
if b==1: b=0
else: b=1
l.append((a,b))
l2 = sorted(l)
gap = 3
num = 2
o = 2
d = {}
d2 = {}
min1 = {}
for i in range(m):
if l2[i] not in d:
d[l2[i]] = []
d2[l2[i]] = 0
if l2[i][1]==0:
if o>n:
print(-1)
exit()
min1[o]=l2[i][0]
d[l2[i]].append((1, o))
o += 1
continue
if num==gap:
num = 2
gap += 1
if l2[i][1]:
if gap in min1 and l2[i][0] < min1[gap]:
print(-1)
exit()
else:
min1[gap] = l2[i][0]
d[l2[i]].append((num, gap))
num += 1
for i in l:
a = d[i][d2[i]]
print(a[0], a[1])
d2[i] += 1
d = {}
``` | instruction | 0 | 93,954 | 13 | 187,908 |
No | output | 1 | 93,954 | 13 | 187,909 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph β something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) β the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 β€ aj β€ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 β€ uj, vj β€ n, uj β vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1
Submitted Solution:
```
n, m = map(int, input().split())
arr = []
for i in range(m):
a, b = map(int, input().split())
arr.append([a, -b, i+1])
arr.sort()
ok = True
for i in range(n-1):
if(arr[i][1] == 0):
ok = False
break
if(ok):
ans = [[-1, -1] for i in range(m)]
for i in range(1, n):
ans[arr[i - 1][2] - 1] = [i, i+1]
at = 1
sec = at + 2
for i in range(n-1, m):
ans[arr[i][2] - 1] = [at, sec]
sec += 1
if(sec == n+1):
at += 1
sec = at + 2
for i in ans:
print(*i)
else:
print(-1)
``` | instruction | 0 | 93,955 | 13 | 187,910 |
No | output | 1 | 93,955 | 13 | 187,911 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph β something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) β the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 β€ aj β€ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 β€ uj, vj β€ n, uj β vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1
Submitted Solution:
```
n,m = map(int, input().split())
l = []
for i in range(m):
a,b = map(int, input().split())
if b==1: b=0
else: b=1
l.append((a,b))
l2 = sorted(l)
t = 1
gap = 1
num = 1
d = {}
d2 = {}
for i in range(m):
if t==0 and l2[i][1]==0:
print(-1)
exit()
if l2[i][1]==1:
t = 0
if num+gap>n:
num = 1
gap += 1
if l2[i] not in d:
d[l2[i]] = []
d2[l2[i]] = 0
d[l2[i]].append((num, num+gap))
num += 1
for i in l:
a = d[i][d2[i]]
print(a[0], a[1])
d2[i] += 1
d = {}
``` | instruction | 0 | 93,956 | 13 | 187,912 |
No | output | 1 | 93,956 | 13 | 187,913 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from 1 to n. For every edge e of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge e (and only this edge) is erased from the tree.
Monocarp has given you a list of n - 1 pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
Input
The first line contains one integer n (2 β€ n β€ 1 000) β the number of vertices in the tree.
Each of the next n-1 lines contains two integers a_i and b_i each (1 β€ a_i < b_i β€ n) β the maximal indices of vertices in the components formed if the i-th edge is removed.
Output
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next n - 1 lines. Each of the last n - 1 lines should contain two integers x_i and y_i (1 β€ x_i, y_i β€ n) β vertices connected by an edge.
Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
Examples
Input
4
3 4
1 4
3 4
Output
YES
1 3
3 2
2 4
Input
3
1 3
1 3
Output
NO
Input
3
1 2
2 3
Output
NO
Note
Possible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
<image> | instruction | 0 | 94,397 | 13 | 188,794 |
Tags: constructive algorithms, data structures, graphs, greedy
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
#import threading
from collections import defaultdict
#threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
#sys.setrecursionlimit(300000)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=300006, func=lambda a, b: min(a , b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b:a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] <=key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
class TrieNode:
def __init__(self):
self.children = [None] * 26
self.isEndOfWord = False
class Trie:
def __init__(self):
self.root = self.getNode()
def getNode(self):
return TrieNode()
def _charToIndex(self, ch):
return ord(ch) - ord('a')
def insert(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
pCrawl.children[index] = self.getNode()
pCrawl = pCrawl.children[index]
pCrawl.isEndOfWord = True
def search(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
return False
pCrawl = pCrawl.children[index]
return pCrawl != None and pCrawl.isEndOfWord
#-----------------------------------------trie---------------------------------
class Node:
def __init__(self, data):
self.data = data
self.count=0
self.left = None # left node for 0
self.right = None # right node for 1
class BinaryTrie:
def __init__(self):
self.root = Node(0)
def insert(self, pre_xor):
self.temp = self.root
for i in range(31, -1, -1):
val = pre_xor & (1 << i)
if val:
if not self.temp.right:
self.temp.right = Node(0)
self.temp = self.temp.right
self.temp.count+=1
if not val:
if not self.temp.left:
self.temp.left = Node(0)
self.temp = self.temp.left
self.temp.count += 1
self.temp.data = pre_xor
def query(self, xor):
self.temp = self.root
for i in range(31, -1, -1):
val = xor & (1 << i)
if not val:
if self.temp.left and self.temp.left.count>0:
self.temp = self.temp.left
elif self.temp.right:
self.temp = self.temp.right
else:
if self.temp.right and self.temp.right.count>0:
self.temp = self.temp.right
elif self.temp.left:
self.temp = self.temp.left
self.temp.count-=1
return xor ^ self.temp.data
#-------------------------bin trie-------------------------------------------
n=int(input())
ans=[]
f=0
d=defaultdict(int)
for i in range(n-1):
a,b=map(int,input().split())
if b!=n:
f=1
d[a]+=1
t=n-1
if f==1:
print("NO")
sys.exit(0)
for i in sorted(d,reverse=True):
last=i
t=min(t,i-1)
while t in d:
t -= 1
for j in range(d[i]-1):
if t<=0:
print("NO")
sys.exit(0)
ans.append((last,t))
last=t
t-=1
while t in d:
t -= 1
ans.append((n,last))
print("YES")
for i in range(n-1):
print(*ans[i])
``` | output | 1 | 94,397 | 13 | 188,795 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from 1 to n. For every edge e of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge e (and only this edge) is erased from the tree.
Monocarp has given you a list of n - 1 pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
Input
The first line contains one integer n (2 β€ n β€ 1 000) β the number of vertices in the tree.
Each of the next n-1 lines contains two integers a_i and b_i each (1 β€ a_i < b_i β€ n) β the maximal indices of vertices in the components formed if the i-th edge is removed.
Output
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next n - 1 lines. Each of the last n - 1 lines should contain two integers x_i and y_i (1 β€ x_i, y_i β€ n) β vertices connected by an edge.
Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
Examples
Input
4
3 4
1 4
3 4
Output
YES
1 3
3 2
2 4
Input
3
1 3
1 3
Output
NO
Input
3
1 2
2 3
Output
NO
Note
Possible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
<image> | instruction | 0 | 94,398 | 13 | 188,796 |
Tags: constructive algorithms, data structures, graphs, greedy
Correct Solution:
```
input=__import__('sys').stdin.readline
n = int(input())
lis=[]
fre=[0]*(10005)
c1=0
ans=[[0,0]]
has=[0]*10005
for i in range(n-1):
a,b = map(int,input().split())
if b<n:
print("NO")
exit()
lis.append(a)
fre[a]+=1
lis.sort()
for i in range(n-1):
if lis[i]<=i:
print("NO")
exit()
else:
zer=1
for i in range(1,n):
if fre[i]==1:
ans.append([i,n])
elif fre[i]>1:
co=0
while co!=fre[i]-1:
if fre[zer]==0 and co==0:
co+=1
ans.append([zer,n])
elif fre[zer]==0:
co+=1
ans.append([zer,ans[-1][0]])
zer+=1
ans.append([i,ans[-1][0]])
print("YES")
for i in ans[1:]:
print(*i)
``` | output | 1 | 94,398 | 13 | 188,797 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from 1 to n. For every edge e of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge e (and only this edge) is erased from the tree.
Monocarp has given you a list of n - 1 pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
Input
The first line contains one integer n (2 β€ n β€ 1 000) β the number of vertices in the tree.
Each of the next n-1 lines contains two integers a_i and b_i each (1 β€ a_i < b_i β€ n) β the maximal indices of vertices in the components formed if the i-th edge is removed.
Output
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next n - 1 lines. Each of the last n - 1 lines should contain two integers x_i and y_i (1 β€ x_i, y_i β€ n) β vertices connected by an edge.
Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
Examples
Input
4
3 4
1 4
3 4
Output
YES
1 3
3 2
2 4
Input
3
1 3
1 3
Output
NO
Input
3
1 2
2 3
Output
NO
Note
Possible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
<image> | instruction | 0 | 94,399 | 13 | 188,798 |
Tags: constructive algorithms, data structures, graphs, greedy
Correct Solution:
```
#
def solve():
n = int(input())
d = {}
for _ in range(n-1):
u, v = map(int, input().split())
min_ = min(u, v)
max_ = max(u, v)
if max_ != n:
return False, None
if min_ not in d:
d[min_] = 0
d[min_] += 1
if sum(list(d.values())) + 1 != n:
return False, None
edge = []
used = {i:False for i in range(1, n+1)}
for k in sorted(list(d.keys())):
used[k] = True
mid = [n]
for i in range(k-1, 0, -1): # k-1->1
if len(mid) == d[k]:
break
if used[i] == False:
used[i] = True
mid.append(i)
if len(mid) < d[k]:
return False, None
mid.append(k)
for u, v in zip(mid[:-1], mid[1:]):
edge.append([u, v])
return True, edge
ans, arr = solve()
if ans == False:
print('NO')
else:
print('YES')
for u, v in arr:
print(str(u)+' '+str(v))
#4
#3 4
#1 4
#3 4
``` | output | 1 | 94,399 | 13 | 188,799 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from 1 to n. For every edge e of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge e (and only this edge) is erased from the tree.
Monocarp has given you a list of n - 1 pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
Input
The first line contains one integer n (2 β€ n β€ 1 000) β the number of vertices in the tree.
Each of the next n-1 lines contains two integers a_i and b_i each (1 β€ a_i < b_i β€ n) β the maximal indices of vertices in the components formed if the i-th edge is removed.
Output
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next n - 1 lines. Each of the last n - 1 lines should contain two integers x_i and y_i (1 β€ x_i, y_i β€ n) β vertices connected by an edge.
Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
Examples
Input
4
3 4
1 4
3 4
Output
YES
1 3
3 2
2 4
Input
3
1 3
1 3
Output
NO
Input
3
1 2
2 3
Output
NO
Note
Possible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
<image> | instruction | 0 | 94,400 | 13 | 188,800 |
Tags: constructive algorithms, data structures, graphs, greedy
Correct Solution:
```
n = int(input())
indices = []
for i in range(n-1):
x, y = map(int, input().split())
indices.append((x, y))
try:
not_seen = set(list(range(1, n)))
seen = {}
for x, y in indices:
assert(x == n or y == n)
seen.setdefault(min(x, y), 0)
seen[min(x, y)] += 1
if min(x, y) in not_seen:
not_seen.remove(min(x, y))
not_seen = sorted(list(not_seen), reverse=True)
seen_list = list(seen.keys())
seen_list.sort(reverse=True)
edges = []
while seen_list:
cur_elem = seen_list.pop(0)
prev = n
while seen[cur_elem] != 1:
assert(not_seen[0] < cur_elem)
next_elem = not_seen.pop(0)
edges.append((prev, next_elem))
prev = next_elem
seen[cur_elem] -= 1
edges.append((prev, cur_elem))
print("YES")
for x, y in edges:
print(x, y)
except AssertionError:
print("NO")
``` | output | 1 | 94,400 | 13 | 188,801 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from 1 to n. For every edge e of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge e (and only this edge) is erased from the tree.
Monocarp has given you a list of n - 1 pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
Input
The first line contains one integer n (2 β€ n β€ 1 000) β the number of vertices in the tree.
Each of the next n-1 lines contains two integers a_i and b_i each (1 β€ a_i < b_i β€ n) β the maximal indices of vertices in the components formed if the i-th edge is removed.
Output
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next n - 1 lines. Each of the last n - 1 lines should contain two integers x_i and y_i (1 β€ x_i, y_i β€ n) β vertices connected by an edge.
Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
Examples
Input
4
3 4
1 4
3 4
Output
YES
1 3
3 2
2 4
Input
3
1 3
1 3
Output
NO
Input
3
1 2
2 3
Output
NO
Note
Possible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
<image> | instruction | 0 | 94,401 | 13 | 188,802 |
Tags: constructive algorithms, data structures, graphs, greedy
Correct Solution:
```
n = int(input())
V = []
for _ in range(n-1):
a,b = map(int, input().split())
V.append(a)
if b <n:
print('NO')
quit()
V.sort()
for i in range(n-1):
if V[i]<=i:
print("NO")
quit()
used = [False]*(n+1)
tree = []
for i in range(n-1):
v = V[i]
if not used[v]:
tree.append(v)
used[v]=True
else:
for j in range(1,n+1):
if not used[j]:
tree.append(j)
used[j] = True
break
tree.append(n)
print("YES")
for i in range(n-1):
print(tree[i],tree[i+1])
``` | output | 1 | 94,401 | 13 | 188,803 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from 1 to n. For every edge e of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge e (and only this edge) is erased from the tree.
Monocarp has given you a list of n - 1 pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
Input
The first line contains one integer n (2 β€ n β€ 1 000) β the number of vertices in the tree.
Each of the next n-1 lines contains two integers a_i and b_i each (1 β€ a_i < b_i β€ n) β the maximal indices of vertices in the components formed if the i-th edge is removed.
Output
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next n - 1 lines. Each of the last n - 1 lines should contain two integers x_i and y_i (1 β€ x_i, y_i β€ n) β vertices connected by an edge.
Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
Examples
Input
4
3 4
1 4
3 4
Output
YES
1 3
3 2
2 4
Input
3
1 3
1 3
Output
NO
Input
3
1 2
2 3
Output
NO
Note
Possible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
<image> | instruction | 0 | 94,402 | 13 | 188,804 |
Tags: constructive algorithms, data structures, graphs, greedy
Correct Solution:
```
from sys import stdin
def bad():
print('NO')
exit()
all_in = stdin.readlines()
n = int(all_in[0])
pair = list(map(lambda x: tuple(map(int, x.split())), all_in[1:]))
f = True
for i in range(n - 1):
if pair[i][0] == n - 1:
f = False
if pair[i][1] != n:
bad()
if f:
bad()
pair.sort(key=lambda x: x[0])
p = list(map(lambda x: x[0], pair))
ans = [0 for i in range(n)]
st = set(range(1, n))
ans[0] = p[0]
st.remove(p[0])
a, b = 0, p[0]
for i in range(1, n - 1):
a, b = b, p[i]
if b != a:
ans[i] = b
st.remove(b)
ans[-1] = n
max_ = 0
for i in range(n):
el = ans[i]
max_ = max(max_, el)
if not el:
m = min(st)
if m > max_:
bad()
ans[i] = m
st.remove(m)
print('YES')
print('\n'.join(map(lambda i: f'{ans[i - 1]} {ans[i]}', range(1, n))))
``` | output | 1 | 94,402 | 13 | 188,805 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from 1 to n. For every edge e of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge e (and only this edge) is erased from the tree.
Monocarp has given you a list of n - 1 pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
Input
The first line contains one integer n (2 β€ n β€ 1 000) β the number of vertices in the tree.
Each of the next n-1 lines contains two integers a_i and b_i each (1 β€ a_i < b_i β€ n) β the maximal indices of vertices in the components formed if the i-th edge is removed.
Output
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next n - 1 lines. Each of the last n - 1 lines should contain two integers x_i and y_i (1 β€ x_i, y_i β€ n) β vertices connected by an edge.
Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
Examples
Input
4
3 4
1 4
3 4
Output
YES
1 3
3 2
2 4
Input
3
1 3
1 3
Output
NO
Input
3
1 2
2 3
Output
NO
Note
Possible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
<image> | instruction | 0 | 94,403 | 13 | 188,806 |
Tags: constructive algorithms, data structures, graphs, greedy
Correct Solution:
```
from copy import deepcopy
import itertools
from bisect import bisect_left
from bisect import bisect_right
import math
from collections import deque
from collections import Counter
def read():
return int(input())
def readmap():
return map(int, input().split())
def readlist():
return list(map(int, input().split()))
n = read()
V = []
for _ in range(n-1):
a, b = readmap()
V.append(a)
if b < n:
print("NO")
quit()
V.sort()
for i in range(n-1):
if V[i] <= i:
print("NO")
quit()
used = [False] * (n+1)
tree = []
for i in range(n-1):
v = V[i]
if not used[v]:
tree.append(v)
used[v] = True
else:
for j in range(1, n+1):
if not used[j]:
tree.append(j)
used[j] = True
break
tree.append(n)
print("YES")
for i in range(n-1):
print(tree[i], tree[i+1])
``` | output | 1 | 94,403 | 13 | 188,807 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from 1 to n. For every edge e of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge e (and only this edge) is erased from the tree.
Monocarp has given you a list of n - 1 pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
Input
The first line contains one integer n (2 β€ n β€ 1 000) β the number of vertices in the tree.
Each of the next n-1 lines contains two integers a_i and b_i each (1 β€ a_i < b_i β€ n) β the maximal indices of vertices in the components formed if the i-th edge is removed.
Output
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next n - 1 lines. Each of the last n - 1 lines should contain two integers x_i and y_i (1 β€ x_i, y_i β€ n) β vertices connected by an edge.
Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
Examples
Input
4
3 4
1 4
3 4
Output
YES
1 3
3 2
2 4
Input
3
1 3
1 3
Output
NO
Input
3
1 2
2 3
Output
NO
Note
Possible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
<image> | instruction | 0 | 94,404 | 13 | 188,808 |
Tags: constructive algorithms, data structures, graphs, greedy
Correct Solution:
```
from bisect import bisect
from collections import defaultdict
# l = list(map(int,input().split()))
# map(int,input().split()))
from math import gcd,sqrt,ceil
from collections import Counter
import sys
sys.setrecursionlimit(10**9)
ans = []
n = int(input())
ba = [i for i in range(1,n+1)]
yo = set(i for i in range(1,n+1))
la = []
hash = defaultdict(int)
for i in range(n-1):
a,b = map(int,input().split())
la.append([max(a,b),min(a,b)])
if a!=n and b!=n:
print('NO')
exit()
if a == b:
print('NO')
exit()
hash[min(a,b)]+=1
seti = set()
for i in range(1,n):
z = hash[i]
j = i-2
if z == 0:
continue
if z == 1:
ans.append([i,n])
yo.remove(i)
continue
z-=1
if z>j:
print('NO')
exit()
if j<0:
print('NO')
exit()
now = i
ha = []
count = 0
while j>=0:
if count == z:
break
if ba[j] in yo:
ans.append([now,ba[j]])
yo.remove(now)
now = ba[j]
j-=1
count+=1
else:
j-=1
if count!=z:
print('NO')
exit()
yo.remove(ans[-1][1])
ans.append([ans[-1][1],n])
print('YES')
for a,b in ans:
print(a,b)
``` | output | 1 | 94,404 | 13 | 188,809 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from 1 to n. For every edge e of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge e (and only this edge) is erased from the tree.
Monocarp has given you a list of n - 1 pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
Input
The first line contains one integer n (2 β€ n β€ 1 000) β the number of vertices in the tree.
Each of the next n-1 lines contains two integers a_i and b_i each (1 β€ a_i < b_i β€ n) β the maximal indices of vertices in the components formed if the i-th edge is removed.
Output
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next n - 1 lines. Each of the last n - 1 lines should contain two integers x_i and y_i (1 β€ x_i, y_i β€ n) β vertices connected by an edge.
Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
Examples
Input
4
3 4
1 4
3 4
Output
YES
1 3
3 2
2 4
Input
3
1 3
1 3
Output
NO
Input
3
1 2
2 3
Output
NO
Note
Possible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
<image>
Submitted Solution:
```
from sys import stdin, stdout
# 4
# 1 4
# 3 4
# 3 4
def three_reconstruction(n, ab_a):
res = []
cnt = [0] * (n + 1)
for ab in ab_a:
a, b = ab
if (a != n and b != n) or a == b:
return [False]
cnt[min(a, b)] += 1
cur = 0
for i in range(1, n+1):
cur += cnt[i]
if cur > i:
return [False]
hs = set()
for i in range(1, n + 1):
hs.add(i)
# print(hs)
last = -1
for i in range(1, n+1):
if cnt[i] > 0:
hs.remove(i)
if last != -1:
res.append([last, i])
last = i
cnt[i] -= 1
while cnt[i] > 0:
v = min(hs)
res.append([last, v])
last = v
cnt[i] -= 1
hs.remove(v)
res.append([last, n])
return [True, res]
n = int(stdin.readline())
ab_a = []
for _ in range(n-1):
ab_a.append(list(map(int, stdin.readline().split())))
res = three_reconstruction(n, ab_a)
if res[0]:
stdout.write('YES\n')
for p in res[1]:
stdout.write(str(p[0]) + ' ' + str(p[1]) + '\n')
else:
stdout.write('NO\n')
``` | instruction | 0 | 94,405 | 13 | 188,810 |
Yes | output | 1 | 94,405 | 13 | 188,811 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from 1 to n. For every edge e of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge e (and only this edge) is erased from the tree.
Monocarp has given you a list of n - 1 pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
Input
The first line contains one integer n (2 β€ n β€ 1 000) β the number of vertices in the tree.
Each of the next n-1 lines contains two integers a_i and b_i each (1 β€ a_i < b_i β€ n) β the maximal indices of vertices in the components formed if the i-th edge is removed.
Output
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next n - 1 lines. Each of the last n - 1 lines should contain two integers x_i and y_i (1 β€ x_i, y_i β€ n) β vertices connected by an edge.
Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
Examples
Input
4
3 4
1 4
3 4
Output
YES
1 3
3 2
2 4
Input
3
1 3
1 3
Output
NO
Input
3
1 2
2 3
Output
NO
Note
Possible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
<image>
Submitted Solution:
```
n = int(input())
a = []
fr = [0]*10000
for i in range(n-1):
x,y = map(int,input().split())
if x == y or (x < n and y < n):
print("NO")
exit(0)
if x == n:
a.append(y)
else:
a.append(x)
b = []
for i in range(1,n+1):
if i not in a:
b.append(i)
for i in a:
if fr[i] == 0:
fr[i] = n
continue
tep = 0
record = 0
for j in range(len(b)):
if b[j] and b[j]<i:
if b[j]>tep:
tep = b[j]
record = j
b[record] = 0
if tep == 0:
print("NO")
exit(0)
fr[tep] = fr[i]
fr[i] = tep
print("YES")
for i in range(1,n):
print(i,fr[i])
``` | instruction | 0 | 94,406 | 13 | 188,812 |
Yes | output | 1 | 94,406 | 13 | 188,813 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from 1 to n. For every edge e of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge e (and only this edge) is erased from the tree.
Monocarp has given you a list of n - 1 pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
Input
The first line contains one integer n (2 β€ n β€ 1 000) β the number of vertices in the tree.
Each of the next n-1 lines contains two integers a_i and b_i each (1 β€ a_i < b_i β€ n) β the maximal indices of vertices in the components formed if the i-th edge is removed.
Output
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next n - 1 lines. Each of the last n - 1 lines should contain two integers x_i and y_i (1 β€ x_i, y_i β€ n) β vertices connected by an edge.
Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
Examples
Input
4
3 4
1 4
3 4
Output
YES
1 3
3 2
2 4
Input
3
1 3
1 3
Output
NO
Input
3
1 2
2 3
Output
NO
Note
Possible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
<image>
Submitted Solution:
```
import sys
n = int(input())
mentioned = [0] * (n - 1)
for _ in range(n-1):
a, b = map(int, input().split())
if b != n:
print("NO")
sys.exit()
else:
mentioned[a-1] += 1
if mentioned[a-1] > a:
print("NO")
sys.exit()
if mentioned[-1] == 0:
print("NO")
sys.exit()
cnt = 0
for i in range(n - 2, -1, -1):
cnt += mentioned[i] - 1
if cnt < 0:
print("NO")
sys.exit()
print("YES")
end = [i for i in range(n - 1) if mentioned[i] > 0]
mid = [i for i in range(n - 1) if mentioned[i] == 0]
#for i in range(1, len(end)):
# branch = [end[i] + 1]
# branch += list(range(end[i-1] + 2, end[i] + 1))
# branch.append(n)
# for j in range(len(branch) - 1):
# print(branch[j], branch[j + 1])
branch_sum = [mentioned[end[0]] - 1]
for i in range(1, len(end)):
branch_sum.append(branch_sum[-1] + mentioned[end[i]] - 1)
branch = [[] for _ in range(len(end))]
branch[0] = mid[:branch_sum[0]]
for i in range(1, len(end)):
branch[i] = mid[branch_sum[i-1]:branch_sum[i]]
#print(end)
#print(branch)
for i in range(len(end)):
ans = [end[i] + 1]
ans += [j + 1 for j in branch[i]]
ans.append(n)
for j in range(len(ans) - 1):
print(ans[j], ans[j + 1])
``` | instruction | 0 | 94,407 | 13 | 188,814 |
Yes | output | 1 | 94,407 | 13 | 188,815 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from 1 to n. For every edge e of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge e (and only this edge) is erased from the tree.
Monocarp has given you a list of n - 1 pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
Input
The first line contains one integer n (2 β€ n β€ 1 000) β the number of vertices in the tree.
Each of the next n-1 lines contains two integers a_i and b_i each (1 β€ a_i < b_i β€ n) β the maximal indices of vertices in the components formed if the i-th edge is removed.
Output
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next n - 1 lines. Each of the last n - 1 lines should contain two integers x_i and y_i (1 β€ x_i, y_i β€ n) β vertices connected by an edge.
Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
Examples
Input
4
3 4
1 4
3 4
Output
YES
1 3
3 2
2 4
Input
3
1 3
1 3
Output
NO
Input
3
1 2
2 3
Output
NO
Note
Possible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
<image>
Submitted Solution:
```
n=int(input())
count1=0
count2=0
arr=[]
arr1=[]
arr2=[]
for i in range(n-1):
x,y=map(int,input().split())
arr.append((x,y))
arr1.append(x)
if(y==n):
count1+=1
if(x==1):
count2+=1
if(count1<n-1 or count2>1):
print('NO')
else:
arr.sort()
i=1
arry=[]
arry.append((arr[0][0],arr[1][0]))
val1=arr[1][0]
val2=arr[0][0]
arrx=[0]*(n+1)
arrx[arr[0][0]]=1
flag=0
while(i<n-1):
if(val1-val2!=arr1.count(val1)):
flag=1
break
while(val1>val2):
val3=val1-1
while(arrx[val3]==1 and val3>0):
val3-=1
if(val3>0):
arry.append((val1,val3))
arrx[val1]=1
val1=val3
i+=1
#print(arry)
else:
break
if(i<n-2):
arry.append((val1,arr[i+1][0]))
arrx[val1]=1
val2=val1
val1=arr[i+1][0]
i+=1
#print(i,arry,val1,val2)
if(flag==1):
print('NO')
else:
arry.append((val1,n))
print('YES')
for i in range(n-1):
print(arry[i][0],arry[i][1])
``` | instruction | 0 | 94,408 | 13 | 188,816 |
No | output | 1 | 94,408 | 13 | 188,817 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from 1 to n. For every edge e of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge e (and only this edge) is erased from the tree.
Monocarp has given you a list of n - 1 pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
Input
The first line contains one integer n (2 β€ n β€ 1 000) β the number of vertices in the tree.
Each of the next n-1 lines contains two integers a_i and b_i each (1 β€ a_i < b_i β€ n) β the maximal indices of vertices in the components formed if the i-th edge is removed.
Output
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next n - 1 lines. Each of the last n - 1 lines should contain two integers x_i and y_i (1 β€ x_i, y_i β€ n) β vertices connected by an edge.
Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
Examples
Input
4
3 4
1 4
3 4
Output
YES
1 3
3 2
2 4
Input
3
1 3
1 3
Output
NO
Input
3
1 2
2 3
Output
NO
Note
Possible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
<image>
Submitted Solution:
```
n=int(input())
count1=0
count2=0
arr=[]
arr1=[]
arr2=[]
for i in range(n-1):
x,y=map(int,input().split())
arr.append((x,y))
arr1.append(x)
if(y==n):
count1+=1
if(x==1):
count2+=1
if(count1<n-1 or count2>1):
print('NO')
else:
arr.sort()
i=1
arry=[]
arry.append((arr[0][0],arr[1][0]))
val1=arr[1][0]
val2=arr[0][0]
arrx=[0]*(n+1)
arrx[arr[0][0]]=1
flag=0
while(i<n-1):
if(i>arr1.count(val1)+i):
flag=1
break
while(val1>val2):
val3=val1-1
while(arrx[val3]==1 and val3>0):
val3-=1
if(val3>0):
arry.append((val1,val3))
arrx[val1]=1
val1=val3
i+=1
#print(arry)
else:
break
if(i<n-2):
arry.append((val1,arr[i+1][0]))
arrx[val1]=1
val2=val1
val1=arr[i+1][0]
i+=1
#print(i,arry,val1,val2)
if(flag==1):
print('NO')
else:
arry.append((val1,n))
print('YES')
for i in range(n-1):
print(arry[i][0],arry[i][1])
``` | instruction | 0 | 94,409 | 13 | 188,818 |
No | output | 1 | 94,409 | 13 | 188,819 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from 1 to n. For every edge e of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge e (and only this edge) is erased from the tree.
Monocarp has given you a list of n - 1 pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
Input
The first line contains one integer n (2 β€ n β€ 1 000) β the number of vertices in the tree.
Each of the next n-1 lines contains two integers a_i and b_i each (1 β€ a_i < b_i β€ n) β the maximal indices of vertices in the components formed if the i-th edge is removed.
Output
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next n - 1 lines. Each of the last n - 1 lines should contain two integers x_i and y_i (1 β€ x_i, y_i β€ n) β vertices connected by an edge.
Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
Examples
Input
4
3 4
1 4
3 4
Output
YES
1 3
3 2
2 4
Input
3
1 3
1 3
Output
NO
Input
3
1 2
2 3
Output
NO
Note
Possible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
<image>
Submitted Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
#import threading
from collections import defaultdict
#threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
#sys.setrecursionlimit(300000)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=300006, func=lambda a, b: min(a , b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b:a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] <=key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
class TrieNode:
def __init__(self):
self.children = [None] * 26
self.isEndOfWord = False
class Trie:
def __init__(self):
self.root = self.getNode()
def getNode(self):
return TrieNode()
def _charToIndex(self, ch):
return ord(ch) - ord('a')
def insert(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
pCrawl.children[index] = self.getNode()
pCrawl = pCrawl.children[index]
pCrawl.isEndOfWord = True
def search(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
return False
pCrawl = pCrawl.children[index]
return pCrawl != None and pCrawl.isEndOfWord
#-----------------------------------------trie---------------------------------
class Node:
def __init__(self, data):
self.data = data
self.count=0
self.left = None # left node for 0
self.right = None # right node for 1
class BinaryTrie:
def __init__(self):
self.root = Node(0)
def insert(self, pre_xor):
self.temp = self.root
for i in range(31, -1, -1):
val = pre_xor & (1 << i)
if val:
if not self.temp.right:
self.temp.right = Node(0)
self.temp = self.temp.right
self.temp.count+=1
if not val:
if not self.temp.left:
self.temp.left = Node(0)
self.temp = self.temp.left
self.temp.count += 1
self.temp.data = pre_xor
def query(self, xor):
self.temp = self.root
for i in range(31, -1, -1):
val = xor & (1 << i)
if not val:
if self.temp.left and self.temp.left.count>0:
self.temp = self.temp.left
elif self.temp.right:
self.temp = self.temp.right
else:
if self.temp.right and self.temp.right.count>0:
self.temp = self.temp.right
elif self.temp.left:
self.temp = self.temp.left
self.temp.count-=1
return xor ^ self.temp.data
#-------------------------bin trie-------------------------------------------
n=int(input())
ans=[]
f=0
d=defaultdict(int)
for i in range(n-1):
a,b=map(int,input().split())
if b!=n:
f=1
d[a]+=1
t=n-1
if f==1:
print("NO")
sys.exit(0)
for i in sorted(d,reverse=True):
last=i
t=min(t,i-1)
while t in d:
t -= 1
for j in range(d[i]-1):
if t<=0:
print("NO")
sys.exit(0)
ans.append((last,t))
last=t
ans.append((n,last))
print("YES")
for i in range(n-1):
print(*ans[i])
``` | instruction | 0 | 94,410 | 13 | 188,820 |
No | output | 1 | 94,410 | 13 | 188,821 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from 1 to n. For every edge e of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge e (and only this edge) is erased from the tree.
Monocarp has given you a list of n - 1 pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
Input
The first line contains one integer n (2 β€ n β€ 1 000) β the number of vertices in the tree.
Each of the next n-1 lines contains two integers a_i and b_i each (1 β€ a_i < b_i β€ n) β the maximal indices of vertices in the components formed if the i-th edge is removed.
Output
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next n - 1 lines. Each of the last n - 1 lines should contain two integers x_i and y_i (1 β€ x_i, y_i β€ n) β vertices connected by an edge.
Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
Examples
Input
4
3 4
1 4
3 4
Output
YES
1 3
3 2
2 4
Input
3
1 3
1 3
Output
NO
Input
3
1 2
2 3
Output
NO
Note
Possible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
<image>
Submitted Solution:
```
#
def solve():
n = int(input())
d = {}
for _ in range(n-1):
u, v = map(int, input().split())
min_ = min(u, v)
max_ = max(u, v)
if max_ != n:
return False, None
if min_ not in d:
d[min_] = 0
d[min_] += 1
if sum(list(d.values())) + 1 != n:
return False, None
edge = []
used = {i:False for i in range(1, n+1)}
for k in sorted(list(d.keys())):
used[k] = True
mid = [n]
for i in range(k-1, 0, -1): # k-1->1
if len(mid) == d[k]:
break
if used[i] == False:
used[i] = True
mid.append(i)
if len(mid) < d[k]:
return False, None
mid.append(k)
for u, v in zip(mid[:-1], mid[1:]):
edge.append([u, v])
return True, edge
ans, arr = solve()
if ans == False:
print('No')
else:
print('Yes')
for u, v in arr:
print(str(u)+' '+str(v))
#4
#3 4
#1 4
#3 4
``` | instruction | 0 | 94,411 | 13 | 188,822 |
No | output | 1 | 94,411 | 13 | 188,823 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 β€ n β€ 10^5, 1 β€ s β€ 10^9) β the number of vertices in the tree and the sum of edge weights.
Each of the following nβ1 lines contains two space-separated integer numbers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} β€ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image> | instruction | 0 | 94,426 | 13 | 188,852 |
Tags: constructive algorithms, implementation, trees
Correct Solution:
```
n, s = map(int, input().split())
gr = {i: [] for i in range(1, n + 1)}
for _ in range(n - 1):
a, b = map(int, input().split())
gr[a].append(b)
gr[b].append(a)
ans = 2 * s / sum([1 if len(gr[i]) == 1 else 0 for i in range(1, n + 1)])
print(ans)
``` | output | 1 | 94,426 | 13 | 188,853 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 β€ n β€ 10^5, 1 β€ s β€ 10^9) β the number of vertices in the tree and the sum of edge weights.
Each of the following nβ1 lines contains two space-separated integer numbers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} β€ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image> | instruction | 0 | 94,427 | 13 | 188,854 |
Tags: constructive algorithms, implementation, trees
Correct Solution:
```
n,s = map(int,input().split())
c = [[] for i in range(n)]
for i in range(n - 1):
a, b = map(int,input().split())
c[a-1].append(b)
c[b-1].append(a)
d = set()
k = 0
for i in range(n):
if len(c[i]) == 1:
d.add(i)
if not (c[i][0] - 1) in d:
k += 1
if n == 2:
print(s)
else:
print(round(s * 2 / k,7))
``` | output | 1 | 94,427 | 13 | 188,855 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 β€ n β€ 10^5, 1 β€ s β€ 10^9) β the number of vertices in the tree and the sum of edge weights.
Each of the following nβ1 lines contains two space-separated integer numbers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} β€ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image> | instruction | 0 | 94,428 | 13 | 188,856 |
Tags: constructive algorithms, implementation, trees
Correct Solution:
```
from collections import Counter
cnt = Counter()
n, s = map(int, input().split())
for _ in range(n-1):
cnt.update(map(int, input().split()))
#print(cnt)
k = sum(cnt[i] == 1 for i in cnt)
print(2*s/k)
``` | output | 1 | 94,428 | 13 | 188,857 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 β€ n β€ 10^5, 1 β€ s β€ 10^9) β the number of vertices in the tree and the sum of edge weights.
Each of the following nβ1 lines contains two space-separated integer numbers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} β€ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image> | instruction | 0 | 94,429 | 13 | 188,858 |
Tags: constructive algorithms, implementation, trees
Correct Solution:
```
n,s=map(int, input().split())
g=[[] for i in range(n+1)]
ind=[0]*n
for i in range(n-1):
u,v=map(int, input().split())
ind[u-1]+=1
ind[v-1]+=1
#g[u-1].append(v-1)
#g[v-1].append(u-1)
ans=0
for i in range(n):
if ind[i]==1:
ans+=1
print(f"{(2*s/ans):.10f}")
``` | output | 1 | 94,429 | 13 | 188,859 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 β€ n β€ 10^5, 1 β€ s β€ 10^9) β the number of vertices in the tree and the sum of edge weights.
Each of the following nβ1 lines contains two space-separated integer numbers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} β€ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image> | instruction | 0 | 94,430 | 13 | 188,860 |
Tags: constructive algorithms, implementation, trees
Correct Solution:
```
# list(map(int, input().split()))
# map(int, input().split())
n, s = map(int, input().split())
g = [[] for i in range(n)]
for i in range(n - 1):
a, b = map(int, input().split())
a -= 1
b -= 1
g[a].append(b)
g[b].append(a)
cnt = 0
for i in range(n):
if len(g[i]) == 1:
cnt += 1
print(2 * s / cnt)
``` | output | 1 | 94,430 | 13 | 188,861 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 β€ n β€ 10^5, 1 β€ s β€ 10^9) β the number of vertices in the tree and the sum of edge weights.
Each of the following nβ1 lines contains two space-separated integer numbers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} β€ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image> | instruction | 0 | 94,431 | 13 | 188,862 |
Tags: constructive algorithms, implementation, trees
Correct Solution:
```
n,s = [int(i) for i in input().split()]
lst = [0 for i in range(n)]
for i in range(n-1):
x,y = [int(i) for i in input().split()]
lst[x-1]+=1
lst[y-1]+=1
count = 0
for i in lst:
if i == 1:
count+=1
print(2*s/count)
``` | output | 1 | 94,431 | 13 | 188,863 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 β€ n β€ 10^5, 1 β€ s β€ 10^9) β the number of vertices in the tree and the sum of edge weights.
Each of the following nβ1 lines contains two space-separated integer numbers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} β€ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image> | instruction | 0 | 94,432 | 13 | 188,864 |
Tags: constructive algorithms, implementation, trees
Correct Solution:
```
n, s = map(int, input().split())
d = {}
for i in range(n - 1):
vertex = list(map(int, input().split()))
d[vertex[0]] = d.get(vertex[0], 0) + 1
d[vertex[1]] = d.get(vertex[1], 0) + 1
c = 0
for i in d:
if d[i] == 1: c += 1
print(2 * s / c)
``` | output | 1 | 94,432 | 13 | 188,865 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 β€ n β€ 10^5, 1 β€ s β€ 10^9) β the number of vertices in the tree and the sum of edge weights.
Each of the following nβ1 lines contains two space-separated integer numbers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} β€ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image> | instruction | 0 | 94,433 | 13 | 188,866 |
Tags: constructive algorithms, implementation, trees
Correct Solution:
```
n, s = map(int, input().split())
dict = {}
for i in range(n - 1):
temp = list(map(int, input().split()))
dict[temp[0]] = dict.get(temp[0], 0) + 1
dict[temp[1]] = dict.get(temp[1], 0) + 1
k = 0
for i in dict:
if dict[i] == 1:
k = k + 1
res = 2 * s / k
print(res)
``` | output | 1 | 94,433 | 13 | 188,867 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 β€ n β€ 10^5, 1 β€ s β€ 10^9) β the number of vertices in the tree and the sum of edge weights.
Each of the following nβ1 lines contains two space-separated integer numbers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} β€ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image>
Submitted Solution:
```
n, k = list(map(int,input().split()))
arr = []
for i in range(n):
arr.append([])
for i in range(n-1):
a,b = list(map(int,input().split()))
a-=1
b-=1
arr[a].append(b)
arr[b].append(a)
c = 0
for i in range(n):
if len(arr[i]) == 1:
c+=1
print((2*k)/c)
``` | instruction | 0 | 94,434 | 13 | 188,868 |
Yes | output | 1 | 94,434 | 13 | 188,869 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 β€ n β€ 10^5, 1 β€ s β€ 10^9) β the number of vertices in the tree and the sum of edge weights.
Each of the following nβ1 lines contains two space-separated integer numbers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} β€ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image>
Submitted Solution:
```
n, s = map(int, input().split())
g = [0 for i in range(n)]
for i in range(n - 1):
a, b = map(int, input().split())
g[a - 1] += 1
g[b - 1] += 1
print((s * 2) / g.count(1))
``` | instruction | 0 | 94,435 | 13 | 188,870 |
Yes | output | 1 | 94,435 | 13 | 188,871 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 β€ n β€ 10^5, 1 β€ s β€ 10^9) β the number of vertices in the tree and the sum of edge weights.
Each of the following nβ1 lines contains two space-separated integer numbers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} β€ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image>
Submitted Solution:
```
def ii():
return int(input())
def mi():
return map(int, input().split())
def li():
return list(mi())
# B. Minimum Diameter Tree
from collections import Counter
n, s = mi()
d = Counter()
for i in range(n - 1):
u, v = mi()
d[u] += 1
d[v] += 1
l = sum(v == 1 for v in d.values())
ans = s / l * 2
print('%.10f' % (ans,))
``` | instruction | 0 | 94,436 | 13 | 188,872 |
Yes | output | 1 | 94,436 | 13 | 188,873 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 β€ n β€ 10^5, 1 β€ s β€ 10^9) β the number of vertices in the tree and the sum of edge weights.
Each of the following nβ1 lines contains two space-separated integer numbers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} β€ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image>
Submitted Solution:
```
n,s=map(int,input().split())
a=[0]*(n+1)
if n==2:
print(s)
exit(0)
for _ in range(n-1):
u,v=map(int,input().split())
a[u]+=1
a[v]+=1
print(2.0*s/a.count(1))
``` | instruction | 0 | 94,437 | 13 | 188,874 |
Yes | output | 1 | 94,437 | 13 | 188,875 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 β€ n β€ 10^5, 1 β€ s β€ 10^9) β the number of vertices in the tree and the sum of edge weights.
Each of the following nβ1 lines contains two space-separated integer numbers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} β€ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image>
Submitted Solution:
```
n, s = map(int, input().split())
d = {}
max_vert = 1
for i in range(n - 1):
vertex = list(map(int, input().split()))
d[vertex[0]] = d.get(vertex[0], 0) + 1
d[vertex[1]] = d.get(vertex[1], 0) + 1
cnt = 0
for i in d:
if d[i] == 1:
cnt += 1
m = max(d.values())
c = 0
for i in d:
if d[i] == m:
c += 1
if c == 1:
print(2 * (s / m))
else:
print(s / ((m - 1) * c))
``` | instruction | 0 | 94,438 | 13 | 188,876 |
No | output | 1 | 94,438 | 13 | 188,877 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 β€ n β€ 10^5, 1 β€ s β€ 10^9) β the number of vertices in the tree and the sum of edge weights.
Each of the following nβ1 lines contains two space-separated integer numbers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} β€ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image>
Submitted Solution:
```
n, s = map(int, input().split())
d = {}
max_vert = 1
for i in range(n - 1):
vertex = list(map(int, input().split()))
d[vertex[0]] = d.get(vertex[0], 0) + 1
d[vertex[1]] = d.get(vertex[1], 0) + 1
cnt = 0
for i in d:
if d[i] == 1:
cnt += 1
m = max(d.values())
c = 0
for i in d:
if d[i] == m:
c += 1
if c == 1:
print(2 * (s / m))
else:
print(2 * (s / ((m - 1) * c)))
``` | instruction | 0 | 94,439 | 13 | 188,878 |
No | output | 1 | 94,439 | 13 | 188,879 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 β€ n β€ 10^5, 1 β€ s β€ 10^9) β the number of vertices in the tree and the sum of edge weights.
Each of the following nβ1 lines contains two space-separated integer numbers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} β€ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image>
Submitted Solution:
```
n,s = map(int,input().split())
c = [[] for i in range(n)]
for i in range(n - 1):
a, b = map(int,input().split())
c[a-1].append(b)
c[b-1].append(a)
d = set()
k = 0
for i in range(n):
if len(c[i]) == 1:
d.add(i)
if not (c[i][0] - 1) in d:
k += 1
print(round(s * 2 / k,10))
``` | instruction | 0 | 94,440 | 13 | 188,880 |
No | output | 1 | 94,440 | 13 | 188,881 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 β€ n β€ 10^5, 1 β€ s β€ 10^9) β the number of vertices in the tree and the sum of edge weights.
Each of the following nβ1 lines contains two space-separated integer numbers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} β€ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image>
Submitted Solution:
```
a, s = list(map(int, input().split()))
graph = [[] for _ in range(a)]
for _ in range(a - 1):
x, y = list(map(int, input().split()))
graph[x-1].append(y-1)
graph[y-1].append(x-1)
k = 0
for i in graph:
if len(i) == 1:
k += 1
print(k)
print((s*2) / k)
``` | instruction | 0 | 94,441 | 13 | 188,882 |
No | output | 1 | 94,441 | 13 | 188,883 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We define a spanning tree of a graph to be a BFS tree rooted at vertex s if and only if for every node t the shortest distance between s and t in the graph is equal to the shortest distance between s and t in the spanning tree.
Given a graph, we define f(x,y) to be the number of spanning trees of that graph that are BFS trees rooted at vertices x and y at the same time.
You are given an undirected connected graph with n vertices and m edges. Calculate f(i,j) for all i, j by modulo 998 244 353.
Input
The first line contains two integers n, m (1 β€ n β€ 400, 0 β€ m β€ 600) β the number of vertices and the number of edges in the graph.
The i-th of the next m lines contains two integers a_i, b_i (1 β€ a_i, b_i β€ n, a_i < b_i), representing an edge connecting a_i and b_i.
It is guaranteed that all edges are distinct and the graph is connected.
Output
Print n lines, each consisting of n integers.
The integer printed in the row i and the column j should be f(i,j) mod 998 244 353.
Examples
Input
4 4
1 2
2 3
3 4
1 4
Output
2 1 0 1
1 2 1 0
0 1 2 1
1 0 1 2
Input
8 9
1 2
1 3
1 4
2 7
3 5
3 6
4 8
2 3
3 4
Output
1 0 0 0 0 0 0 0
0 2 0 0 0 0 2 0
0 0 1 0 1 1 0 0
0 0 0 2 0 0 0 2
0 0 1 0 1 1 0 0
0 0 1 0 1 1 0 0
0 2 0 0 0 0 2 0
0 0 0 2 0 0 0 2
Note
The following picture describes the first example.
<image>
The tree with red edges is a BFS tree rooted at both 1 and 2.
<image>
Similarly, the BFS tree for other adjacent pairs of vertices can be generated in this way. | instruction | 0 | 94,616 | 13 | 189,232 |
Tags: combinatorics, dfs and similar, graphs, math, shortest paths, trees
Correct Solution:
```
import sys, os
from collections import defaultdict, deque
if os.environ['USERNAME']=='kissz':
inp=open('in2.txt','r').readline
def debug(*args):
print(*args,file=sys.stderr)
else:
inp=sys.stdin.readline
def debug(*args):
pass
# SCRIPT STARTS HERE
def solve():
n,m=map(int,inp().split())
G=defaultdict(list)
for i in range(m):
u,v=map(int,inp().split())
G[u-1]+=[v-1]
G[v-1]+=[u-1]
combs=[[-1]*n for _ in range(n)]
def bfs(i):
Q=deque([i])
D=[-1]*n
D[i]=0
while Q:
node=Q.pop()
for neighbor in G[node]:
if D[neighbor]==-1:
Q.appendleft(neighbor)
D[neighbor]=D[node]+1
return D
dists=[bfs(i) for i in range(n)]
for i in range(n):
for j in range(i+1):
node=j
failed=False
while node!=i:
c=0
next_node=-1
for neighbor in G[node]:
if dists[i][neighbor]<dists[i][node]:
c+=1
next_node=neighbor
if c==1:
node=next_node
else:
failed=True
break
call=1
if failed:
combs[i][j]=combs[j][i]=0
else:
for k in range(n):
if dists[i][k]+dists[j][k]>dists[i][j]:
c=0
for l in G[k]:
if dists[i][l]+1==dists[i][k] and dists[j][l]+1==dists[j][k]:
c+=1
call=(call*c)% 998244353
combs[i][j]=combs[j][i]=call
for i in range(n):
print(*combs[i])
solve()
``` | output | 1 | 94,616 | 13 | 189,233 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.