message stringlengths 2 49.9k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 446 108k | cluster float64 13 13 | __index_level_0__ int64 892 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected connected graph consisting of n vertices and m edges. There are no loops and no multiple edges in the graph.
You are also given two distinct vertices s and t, and two values ds and dt. Your task is to build any spanning tree of the given graph (note that the graph is not weighted), such that the degree of the vertex s doesn't exceed ds, and the degree of the vertex t doesn't exceed dt, or determine, that there is no such spanning tree.
The spanning tree of the graph G is a subgraph which is a tree and contains all vertices of the graph G. In other words, it is a connected graph which contains n - 1 edges and can be obtained by removing some of the edges from G.
The degree of a vertex is the number of edges incident to this vertex.
Input
The first line of the input contains two integers n and m (2 ≤ n ≤ 200 000, 1 ≤ m ≤ min(400 000, n·(n - 1) / 2)) — the number of vertices and the number of edges in the graph.
The next m lines contain the descriptions of the graph's edges. Each of the lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the ends of the corresponding edge. It is guaranteed that the graph contains no loops and no multiple edges and that it is connected.
The last line contains four integers s, t, ds, dt (1 ≤ s, t ≤ n, s ≠ t, 1 ≤ ds, dt ≤ n - 1).
Output
If the answer doesn't exist print "No" (without quotes) in the only line of the output.
Otherwise, in the first line print "Yes" (without quotes). In the each of the next (n - 1) lines print two integers — the description of the edges of the spanning tree. Each of the edges of the spanning tree must be printed exactly once.
You can output edges in any order. You can output the ends of each edge in any order.
If there are several solutions, print any of them.
Examples
Input
3 3
1 2
2 3
3 1
1 2 1 1
Output
Yes
3 2
1 3
Input
7 8
7 4
1 3
5 4
5 7
3 2
2 4
6 1
1 2
6 4 1 4
Output
Yes
1 3
5 7
3 2
7 4
2 4
6 1
Submitted Solution:
```
total_vertices, total_edges = map(int, input().split())
graph = [set() for _ in range(total_vertices + 1)]
tree_edges = []
in_tree = [False for _ in range(total_vertices + 1)]
for _ in range(total_edges):
start, end = map(int, input().split())
graph[start].add(end)
graph[end].add(start)
s, t, s_max, t_max = map(int, input().split())
stack = [s]
in_tree[s] = True
while stack:
cur_vertice = stack.pop()
for con_vertice in graph[cur_vertice]:
if not in_tree[con_vertice]:
tree_edges.append(" ".join((str(cur_vertice), str(con_vertice))))
in_tree[con_vertice] = True
stack.append(con_vertice)
for tree_edge in tree_edges:
print(tree_edge)
``` | instruction | 0 | 446 | 13 | 892 |
No | output | 1 | 446 | 13 | 893 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected connected graph consisting of n vertices and m edges. There are no loops and no multiple edges in the graph.
You are also given two distinct vertices s and t, and two values ds and dt. Your task is to build any spanning tree of the given graph (note that the graph is not weighted), such that the degree of the vertex s doesn't exceed ds, and the degree of the vertex t doesn't exceed dt, or determine, that there is no such spanning tree.
The spanning tree of the graph G is a subgraph which is a tree and contains all vertices of the graph G. In other words, it is a connected graph which contains n - 1 edges and can be obtained by removing some of the edges from G.
The degree of a vertex is the number of edges incident to this vertex.
Input
The first line of the input contains two integers n and m (2 ≤ n ≤ 200 000, 1 ≤ m ≤ min(400 000, n·(n - 1) / 2)) — the number of vertices and the number of edges in the graph.
The next m lines contain the descriptions of the graph's edges. Each of the lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the ends of the corresponding edge. It is guaranteed that the graph contains no loops and no multiple edges and that it is connected.
The last line contains four integers s, t, ds, dt (1 ≤ s, t ≤ n, s ≠ t, 1 ≤ ds, dt ≤ n - 1).
Output
If the answer doesn't exist print "No" (without quotes) in the only line of the output.
Otherwise, in the first line print "Yes" (without quotes). In the each of the next (n - 1) lines print two integers — the description of the edges of the spanning tree. Each of the edges of the spanning tree must be printed exactly once.
You can output edges in any order. You can output the ends of each edge in any order.
If there are several solutions, print any of them.
Examples
Input
3 3
1 2
2 3
3 1
1 2 1 1
Output
Yes
3 2
1 3
Input
7 8
7 4
1 3
5 4
5 7
3 2
2 4
6 1
1 2
6 4 1 4
Output
Yes
1 3
5 7
3 2
7 4
2 4
6 1
Submitted Solution:
```
n,m=map(int,input().split())
adj=[[] for i in range(n+1)]
for i in range(m):
x,y=map(int,input().split())
adj[x-1].append(y-1)
adj[y-1].append(x-1)
level = [-1] * len(adj)
def bfs(s):
global level
level[s] = 0
queue = [s]
while queue:
v = queue.pop(0)
for w in adj[v]:
if level[w] is -1:
queue.append(w)
level[w] = level[v] + 1
for i in range(len(adj)):
if level[i] is -1:
bfs(i)
print(*level[:-1])
``` | instruction | 0 | 447 | 13 | 894 |
No | output | 1 | 447 | 13 | 895 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected connected graph consisting of n vertices and m edges. There are no loops and no multiple edges in the graph.
You are also given two distinct vertices s and t, and two values ds and dt. Your task is to build any spanning tree of the given graph (note that the graph is not weighted), such that the degree of the vertex s doesn't exceed ds, and the degree of the vertex t doesn't exceed dt, or determine, that there is no such spanning tree.
The spanning tree of the graph G is a subgraph which is a tree and contains all vertices of the graph G. In other words, it is a connected graph which contains n - 1 edges and can be obtained by removing some of the edges from G.
The degree of a vertex is the number of edges incident to this vertex.
Input
The first line of the input contains two integers n and m (2 ≤ n ≤ 200 000, 1 ≤ m ≤ min(400 000, n·(n - 1) / 2)) — the number of vertices and the number of edges in the graph.
The next m lines contain the descriptions of the graph's edges. Each of the lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the ends of the corresponding edge. It is guaranteed that the graph contains no loops and no multiple edges and that it is connected.
The last line contains four integers s, t, ds, dt (1 ≤ s, t ≤ n, s ≠ t, 1 ≤ ds, dt ≤ n - 1).
Output
If the answer doesn't exist print "No" (without quotes) in the only line of the output.
Otherwise, in the first line print "Yes" (without quotes). In the each of the next (n - 1) lines print two integers — the description of the edges of the spanning tree. Each of the edges of the spanning tree must be printed exactly once.
You can output edges in any order. You can output the ends of each edge in any order.
If there are several solutions, print any of them.
Examples
Input
3 3
1 2
2 3
3 1
1 2 1 1
Output
Yes
3 2
1 3
Input
7 8
7 4
1 3
5 4
5 7
3 2
2 4
6 1
1 2
6 4 1 4
Output
Yes
1 3
5 7
3 2
7 4
2 4
6 1
Submitted Solution:
```
print(4)
``` | instruction | 0 | 448 | 13 | 896 |
No | output | 1 | 448 | 13 | 897 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given a rooted tree with n nodes. The Night King removes exactly one node from the tree and all the edges associated with it. Doing this splits the tree and forms a forest. The node which is removed is not a part of the forest.
The root of a tree in the forest is the node in that tree which does not have a parent. We define the strength of the forest as the size of largest tree in forest.
Jon Snow wants to minimize the strength of the forest. To do this he can perform the following operation at most once.
He removes the edge between a node and its parent and inserts a new edge between this node and any other node in forest such that the total number of trees in forest remain same.
For each node v you need to find the minimum value of strength of the forest formed when node v is removed.
Input
The first line of the input contains an integer n (1 ≤ n ≤ 105) — the number of vertices in the tree. Each of the next n lines contains a pair of vertex indices ui and vi (1 ≤ ui, vi ≤ n) where ui is the parent of vi. If ui = 0 then vi is the root.
Output
Print n line each containing a single integer. The i-th of them should be equal to minimum value of strength of forest formed when i-th node is removed and Jon Snow performs the operation described above at most once.
Examples
Input
10
0 1
1 2
1 3
1 4
2 5
2 6
3 7
4 8
4 9
5 10
Output
3
4
5
5
5
9
9
9
9
9
Input
2
2 1
0 2
Output
1
1
Note
The tree for first test case is depicted below. <image> When you remove the first node, the tree splits to form the following forest. The strength of this forest is 4. <image> Jon Snow now changes the parent of vertex 10 from 5 to 3. The strength of forest now becomes 3. <image>
Submitted Solution:
```
a=input()
b=input()
for i in range(0,len(a)):
if(a[i]==b[i]):
print(0,end='')
else:
print(1,end='')
``` | instruction | 0 | 449 | 13 | 898 |
No | output | 1 | 449 | 13 | 899 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.
Alice starts at vertex 1 and Bob starts at vertex x (x ≠ 1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.
The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.
You should write a program which will determine how many moves will the game last.
Input
The first line contains two integer numbers n and x (2 ≤ n ≤ 2·105, 2 ≤ x ≤ n).
Each of the next n - 1 lines contains two integer numbers a and b (1 ≤ a, b ≤ n) — edges of the tree. It is guaranteed that the edges form a valid tree.
Output
Print the total number of moves Alice and Bob will make.
Examples
Input
4 3
1 2
2 3
2 4
Output
4
Input
5 2
1 2
2 3
3 4
2 5
Output
6
Note
In the first example the tree looks like this:
<image>
The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:
B: stay at vertex 3
A: go to vertex 2
B: stay at vertex 3
A: go to vertex 3
In the second example the tree looks like this:
<image>
The moves in the optimal strategy are:
B: go to vertex 3
A: go to vertex 2
B: go to vertex 4
A: go to vertex 3
B: stay at vertex 4
A: go to vertex 4 | instruction | 0 | 455 | 13 | 910 |
Tags: dfs and similar, graphs
Correct Solution:
```
import sys
from math import *
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
n, x = mints()
e = [[] for i in range(n)]
for i in range(n-1):
a, b = mints()
e[a-1].append(b-1)
e[b-1].append(a-1)
x -= 1
q = [0]*n
d = [0]*n
p = [-1]*n
ql = 0
qr = 1
q[0] = x
d[x] = 1
while ql < qr:
u = q[ql]
ql += 1
for v in e[u]:
if d[v] == 0:
d[v] = d[u] + 1
p[v] = u
q[qr] = v
qr += 1
#v = 0
#u = 1
#while v != -1:
# if d[v] >= u:
# d[v] = 0
# v = p[v]
# u += 1
#print(d)
dd = [0]*n
ql = 0
qr = 1
q[0] = 0
dd[0] = 1
while ql < qr:
u = q[ql]
ql += 1
for v in e[u]:
if dd[v] == 0:
dd[v] = dd[u] + 1
q[qr] = v
qr += 1
r = 0
for i in range(n):
if d[i] < dd[i]:
r = max(r, dd[i])
print((r-1)*2)
``` | output | 1 | 455 | 13 | 911 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.
Alice starts at vertex 1 and Bob starts at vertex x (x ≠ 1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.
The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.
You should write a program which will determine how many moves will the game last.
Input
The first line contains two integer numbers n and x (2 ≤ n ≤ 2·105, 2 ≤ x ≤ n).
Each of the next n - 1 lines contains two integer numbers a and b (1 ≤ a, b ≤ n) — edges of the tree. It is guaranteed that the edges form a valid tree.
Output
Print the total number of moves Alice and Bob will make.
Examples
Input
4 3
1 2
2 3
2 4
Output
4
Input
5 2
1 2
2 3
3 4
2 5
Output
6
Note
In the first example the tree looks like this:
<image>
The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:
B: stay at vertex 3
A: go to vertex 2
B: stay at vertex 3
A: go to vertex 3
In the second example the tree looks like this:
<image>
The moves in the optimal strategy are:
B: go to vertex 3
A: go to vertex 2
B: go to vertex 4
A: go to vertex 3
B: stay at vertex 4
A: go to vertex 4 | instruction | 0 | 456 | 13 | 912 |
Tags: dfs and similar, graphs
Correct Solution:
```
import sys
from collections import deque
n, x = map(int, sys.stdin.buffer.readline().decode('utf-8').split())
x -= 1
adj = [[] for _ in range(n)]
for u, v in (map(int, line.decode('utf-8').split()) for line in sys.stdin.buffer):
adj[u-1].append(v-1)
adj[v-1].append(u-1)
bob = 1
color = [0]*n
color[0] = 1
color[x] = 2
dq = deque()
dq.extend(((x, 2, 1), (0, 1, 2)))
while dq:
v, c, t = dq.popleft()
if c == 2 and color[v] == 1:
continue
for dest in adj[v]:
if color[dest] == c or color[dest] == 1 and c == 2:
continue
if c == 1 and color[dest] == 2:
bob -= 1
if bob == 0:
print(t)
exit()
if c == 2:
bob += 1
color[dest] = c
dq.append((dest, c, t+2))
``` | output | 1 | 456 | 13 | 913 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.
Alice starts at vertex 1 and Bob starts at vertex x (x ≠ 1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.
The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.
You should write a program which will determine how many moves will the game last.
Input
The first line contains two integer numbers n and x (2 ≤ n ≤ 2·105, 2 ≤ x ≤ n).
Each of the next n - 1 lines contains two integer numbers a and b (1 ≤ a, b ≤ n) — edges of the tree. It is guaranteed that the edges form a valid tree.
Output
Print the total number of moves Alice and Bob will make.
Examples
Input
4 3
1 2
2 3
2 4
Output
4
Input
5 2
1 2
2 3
3 4
2 5
Output
6
Note
In the first example the tree looks like this:
<image>
The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:
B: stay at vertex 3
A: go to vertex 2
B: stay at vertex 3
A: go to vertex 3
In the second example the tree looks like this:
<image>
The moves in the optimal strategy are:
B: go to vertex 3
A: go to vertex 2
B: go to vertex 4
A: go to vertex 3
B: stay at vertex 4
A: go to vertex 4 | instruction | 0 | 457 | 13 | 914 |
Tags: dfs and similar, graphs
Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
from collections import deque
def prog():
n,x = map(int,input().split())
adj = [[] for i in range(n + 1)]
for i in range(n-1):
u,v = map(int,input().split())
adj[u].append(v)
adj[v].append(u)
dist = [0]*(n+1)
parent = [0]*(n+1)
visited = [0]*(n+1)
dist2 = [0]*(n+1)
visited2 = [0]*(n+1)
s = deque([1])
while s:
curr = s[-1]
if not visited[curr]:
visited[curr] = 1
for neighbor in adj[curr]:
if not visited[neighbor]:
parent[neighbor] = curr
s.append(neighbor)
dist[neighbor] = dist[curr] + 1
else:
s.pop()
curr = x
moved_up = 0
while moved_up + 1 < dist[parent[curr]]:
curr = parent[curr]
moved_up += 1
s = deque([curr])
while s:
curr = s[-1]
if not visited2[curr]:
visited2[curr] = 1
for neighbor in adj[curr]:
if parent[curr] != neighbor:
s.append(neighbor)
dist2[neighbor] = dist2[curr] + 1
else:
s.pop()
best_loc = 0
best_dist = -1
for i in range(n + 1):
if visited2[i] and dist2[i] > best_dist:
best_dist = dist2[i]
best_loc = i
print(2*dist[best_loc])
prog()
``` | output | 1 | 457 | 13 | 915 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.
Alice starts at vertex 1 and Bob starts at vertex x (x ≠ 1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.
The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.
You should write a program which will determine how many moves will the game last.
Input
The first line contains two integer numbers n and x (2 ≤ n ≤ 2·105, 2 ≤ x ≤ n).
Each of the next n - 1 lines contains two integer numbers a and b (1 ≤ a, b ≤ n) — edges of the tree. It is guaranteed that the edges form a valid tree.
Output
Print the total number of moves Alice and Bob will make.
Examples
Input
4 3
1 2
2 3
2 4
Output
4
Input
5 2
1 2
2 3
3 4
2 5
Output
6
Note
In the first example the tree looks like this:
<image>
The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:
B: stay at vertex 3
A: go to vertex 2
B: stay at vertex 3
A: go to vertex 3
In the second example the tree looks like this:
<image>
The moves in the optimal strategy are:
B: go to vertex 3
A: go to vertex 2
B: go to vertex 4
A: go to vertex 3
B: stay at vertex 4
A: go to vertex 4 | instruction | 0 | 458 | 13 | 916 |
Tags: dfs and similar, graphs
Correct Solution:
```
def prog():
from sys import stdin
from collections import deque
n,x = map(int,stdin.readline().split())
x-=1
d = [[] for i in range(n)]
for i in range(n-1):
a,b = map(int,stdin.readline().split())
d[a-1].append(b-1)
d[b-1].append(a-1)
Alice = [1000000 for i in range(n)]
Bob = [1000000 for i in range(n)]
queue=deque()
queue.append([0,0])
while queue:
q1 = queue.popleft()
Alice[q1[0]]=min(Alice[q1[0]],q1[1])
for i,item in enumerate(d[q1[0]]):
if Alice[item]==1000000:
queue.append([item,q1[1]+1])
queue.append([x,0])
while queue:
q2 = queue.popleft()
Bob[q2[0]]=min(Bob[q2[0]],q2[1])
for i,item in enumerate(d[q2[0]]):
if Bob[item]==1000000:
queue.append([item,q2[1]+1])
res = 0
for i in range(n):
A=Alice[i]
if A>Bob[i]:
if A>res:
res=A
print(2*res)
prog()
``` | output | 1 | 458 | 13 | 917 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.
Alice starts at vertex 1 and Bob starts at vertex x (x ≠ 1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.
The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.
You should write a program which will determine how many moves will the game last.
Input
The first line contains two integer numbers n and x (2 ≤ n ≤ 2·105, 2 ≤ x ≤ n).
Each of the next n - 1 lines contains two integer numbers a and b (1 ≤ a, b ≤ n) — edges of the tree. It is guaranteed that the edges form a valid tree.
Output
Print the total number of moves Alice and Bob will make.
Examples
Input
4 3
1 2
2 3
2 4
Output
4
Input
5 2
1 2
2 3
3 4
2 5
Output
6
Note
In the first example the tree looks like this:
<image>
The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:
B: stay at vertex 3
A: go to vertex 2
B: stay at vertex 3
A: go to vertex 3
In the second example the tree looks like this:
<image>
The moves in the optimal strategy are:
B: go to vertex 3
A: go to vertex 2
B: go to vertex 4
A: go to vertex 3
B: stay at vertex 4
A: go to vertex 4 | instruction | 0 | 459 | 13 | 918 |
Tags: dfs and similar, graphs
Correct Solution:
```
from collections import deque
from sys import stdin
#parsea una linea
def parser():
return map(int, stdin.readline().split())
#Metodo usado para calcular las distancia de un vertice al resto de los vertices
def BFS(s):
distance=[-1 for i in range(n)]
distance[s]=0
q=deque()
q.append(s)
while len(q)>0:
v=q.popleft()
for u in adjacents_list[v]:
if distance[u] == -1:
distance[u]=distance[v]+1
q.append(u)
return distance
#Recibiendo los valores de n y x
n,x=parser()
#Armando el arbol
adjacents_list=[[] for i in range(n)]
for i in range(n-1):
#Leyendo una arista
v1,v2=parser()
adjacents_list[v1-1].append(v2-1)
adjacents_list[v2-1].append(v1-1)
#Hallando las distancias
distance_Alice=BFS(0)
distance_Bob=BFS(x-1)
#Obteniendo la distancia mayor desde el vertice 1 hasta un vertice alcanzable por Bob
max_distance=0
for i in range(n):
if max_distance<distance_Alice[i] and distance_Bob[i]<distance_Alice[i]:
max_distance=distance_Alice[i]
#Imprimiendo el resultado
print(max_distance*2)
``` | output | 1 | 459 | 13 | 919 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.
Alice starts at vertex 1 and Bob starts at vertex x (x ≠ 1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.
The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.
You should write a program which will determine how many moves will the game last.
Input
The first line contains two integer numbers n and x (2 ≤ n ≤ 2·105, 2 ≤ x ≤ n).
Each of the next n - 1 lines contains two integer numbers a and b (1 ≤ a, b ≤ n) — edges of the tree. It is guaranteed that the edges form a valid tree.
Output
Print the total number of moves Alice and Bob will make.
Examples
Input
4 3
1 2
2 3
2 4
Output
4
Input
5 2
1 2
2 3
3 4
2 5
Output
6
Note
In the first example the tree looks like this:
<image>
The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:
B: stay at vertex 3
A: go to vertex 2
B: stay at vertex 3
A: go to vertex 3
In the second example the tree looks like this:
<image>
The moves in the optimal strategy are:
B: go to vertex 3
A: go to vertex 2
B: go to vertex 4
A: go to vertex 3
B: stay at vertex 4
A: go to vertex 4 | instruction | 0 | 460 | 13 | 920 |
Tags: dfs and similar, graphs
Correct Solution:
```
from collections import deque
from sys import stdin
#parser
def parser():
return [int(i) for i in stdin.readline().split(" ")]
#Algoritmo BFS
def BFS(s):
if s==0:
distance=distance_Alice
else:
distance=distance_Bob
distance[s]=0
q=deque()
q.append(s)
while len(q)>0:
v=q.popleft()
for u in adjacents_list[v]:
if distance[u] == -1:
distance[u]=distance[v]+1
q.append(u)
#Recibiendo los valores de n y x
n,x=parser()
#Creando los arrays necesarios para la ejecucion de DFS
#visitados
distance_Alice=[-1 for i in range(n)]
distance_Bob=[-1 for i in range(n)]
#Armando el arbol
adjacents_list=[[] for i in range(n)]
for i in range(n-1):
edge=parser()
adjacents_list[edge[0]-1].append(edge[1]-1)
adjacents_list[edge[1]-1].append(edge[0]-1)
BFS(0)
BFS(x-1)
#Hallando el nodo mas alejado a Alice que puede alcanzar Bob antes que lo alcance Alice
max=0
for i in range(n):
if max<distance_Alice[i] and distance_Bob[i]<distance_Alice[i]:
max=distance_Alice[i]
print(max*2)
``` | output | 1 | 460 | 13 | 921 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.
Alice starts at vertex 1 and Bob starts at vertex x (x ≠ 1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.
The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.
You should write a program which will determine how many moves will the game last.
Input
The first line contains two integer numbers n and x (2 ≤ n ≤ 2·105, 2 ≤ x ≤ n).
Each of the next n - 1 lines contains two integer numbers a and b (1 ≤ a, b ≤ n) — edges of the tree. It is guaranteed that the edges form a valid tree.
Output
Print the total number of moves Alice and Bob will make.
Examples
Input
4 3
1 2
2 3
2 4
Output
4
Input
5 2
1 2
2 3
3 4
2 5
Output
6
Note
In the first example the tree looks like this:
<image>
The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:
B: stay at vertex 3
A: go to vertex 2
B: stay at vertex 3
A: go to vertex 3
In the second example the tree looks like this:
<image>
The moves in the optimal strategy are:
B: go to vertex 3
A: go to vertex 2
B: go to vertex 4
A: go to vertex 3
B: stay at vertex 4
A: go to vertex 4 | instruction | 0 | 461 | 13 | 922 |
Tags: dfs and similar, graphs
Correct Solution:
```
import sys,math,itertools
from collections import Counter,deque,defaultdict
from bisect import bisect_left,bisect_right
from heapq import heappop,heappush,heapify
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_1(): return list(map(lambda x:int(x)-1, sys.stdin.readline().split()))
def inps(): return sys.stdin.readline()
def inpsl(x): tmp = sys.stdin.readline(); return list(tmp[:x])
def err(x): print(x); exit()
n,X = inpl(); X -= 1
g = [[] for _ in range(n)]
for _ in range(n-1):
a,b = inpl_1()
g[a].append(b)
g[b].append(a)
dist = [-1]*n; dist[0] = 0
q = deque([0])
pa = -1
while q:
u = q.popleft()
for v in g[u]:
if dist[v] != -1: continue
if v == X: pa = u
dist[v] = dist[u] + 1
q.append(v)
dist2 = [-1]*n; dist2[X] = 0
q = deque([X])
while q:
u = q.popleft()
for v in g[u]:
if dist2[v] != -1 or dist2[u]+1 >= dist[v]:
continue
dist2[v] = dist2[u] + 1
q.append(v)
# mx = max(dist2)
res = 0
for i in range(n):
if dist2[i] >= 0:
res = max(res, dist[i])
print(res*2)
``` | output | 1 | 461 | 13 | 923 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.
Alice starts at vertex 1 and Bob starts at vertex x (x ≠ 1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.
The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.
You should write a program which will determine how many moves will the game last.
Input
The first line contains two integer numbers n and x (2 ≤ n ≤ 2·105, 2 ≤ x ≤ n).
Each of the next n - 1 lines contains two integer numbers a and b (1 ≤ a, b ≤ n) — edges of the tree. It is guaranteed that the edges form a valid tree.
Output
Print the total number of moves Alice and Bob will make.
Examples
Input
4 3
1 2
2 3
2 4
Output
4
Input
5 2
1 2
2 3
3 4
2 5
Output
6
Note
In the first example the tree looks like this:
<image>
The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:
B: stay at vertex 3
A: go to vertex 2
B: stay at vertex 3
A: go to vertex 3
In the second example the tree looks like this:
<image>
The moves in the optimal strategy are:
B: go to vertex 3
A: go to vertex 2
B: go to vertex 4
A: go to vertex 3
B: stay at vertex 4
A: go to vertex 4 | instruction | 0 | 462 | 13 | 924 |
Tags: dfs and similar, graphs
Correct Solution:
```
from sys import stdin
#Clase nodo
class Node():
def __init__(self,value=None,prox=None):
self.value=value
self.prox=prox
#Clase cola
class Queue:
def __init__(self):
self.first=None
self.last=None
self.count=0
def Enqueue(self,value):
new_node=Node(value)
self.count+=1
if self.first is None:
self.last=self.first=new_node
else:
self.last.prox=new_node
self.last=new_node
def Dequeue(self):
value=self.first.value
self.count-=1
self.first=self.first.prox
return value
#Parser
def parser():
return [int(x) for x in input().split(" ")]
#Algoritmo BFS
def BFS(s):
if s==0:
distance=distance_Alice
else:
distance=distance_Bob
distance[s]=0
q=Queue()
q.Enqueue(s)
while q.count>0:
v=q.Dequeue()
for u in adjacents_list[v]:
if distance[u] == -1:
distance[u]=distance[v]+1
q.Enqueue(u)
#Recibiendo los valores de n y x
n,x=map(int, stdin.readline().split())
#Creando los arrays necesarios para la ejecucion de DFS
#visitados
distance_Alice=[-1 for i in range(n)]
distance_Bob=[-1 for i in range(n)]
#Armando el arbol
adjacents_list=[[] for i in range(n)]
for i in range(n-1):
v1,v2=map(int, stdin.readline().split())
adjacents_list[v1-1].append(v2-1)
adjacents_list[v2-1].append(v1-1)
BFS(0)
BFS(x-1)
#Hallando el nodo mas alejado a Alice que puede alcanzar Bob antes que lo alcance Alice
max=0
for i in range(n):
if max<distance_Alice[i] and distance_Bob[i]<distance_Alice[i]:
max=distance_Alice[i]
print(max*2)
``` | output | 1 | 462 | 13 | 925 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.
Alice starts at vertex 1 and Bob starts at vertex x (x ≠ 1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.
The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.
You should write a program which will determine how many moves will the game last.
Input
The first line contains two integer numbers n and x (2 ≤ n ≤ 2·105, 2 ≤ x ≤ n).
Each of the next n - 1 lines contains two integer numbers a and b (1 ≤ a, b ≤ n) — edges of the tree. It is guaranteed that the edges form a valid tree.
Output
Print the total number of moves Alice and Bob will make.
Examples
Input
4 3
1 2
2 3
2 4
Output
4
Input
5 2
1 2
2 3
3 4
2 5
Output
6
Note
In the first example the tree looks like this:
<image>
The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:
B: stay at vertex 3
A: go to vertex 2
B: stay at vertex 3
A: go to vertex 3
In the second example the tree looks like this:
<image>
The moves in the optimal strategy are:
B: go to vertex 3
A: go to vertex 2
B: go to vertex 4
A: go to vertex 3
B: stay at vertex 4
A: go to vertex 4
Submitted Solution:
```
from collections import deque
from sys import stdin
n, x = map(int, stdin.readline().split())
leafs = set(range(n))
graph = [[] for i in range(n)]
count = [False for i in range(n)]
for i in range(n - 1):
a, b = map(int, stdin.readline().split())
graph[a - 1].append(b - 1)
graph[b - 1].append(a - 1)
if not count[a - 1]:
count[a - 1] = True
else:
leafs.discard(a - 1)
if not count[b - 1]:
count[b - 1] = True
else:
leafs.discard(b - 1)
queue = deque()
way_a = [10 ** 6 for i in range(n)]
way_b = [10 ** 6 for i in range(n)]
used = [False for i in range(n)]
queue.append([0, 0])
while queue:
j = queue.popleft()
way_a[j[0]] = min(way_a[j[0]], j[1])
for i in graph[j[0]]:
if not used[i]:
used[i] = True
queue.append([i, j[1] + 1])
queue.append([x - 1, 0])
used = [False for i in range(n)]
while queue:
j = queue.popleft()
way_b[j[0]] = min(way_b[j[0]], j[1])
for i in graph[j[0]]:
if not used[i]:
used[i] = True
queue.append([i, j[1] + 1])
res = way_a[x - 1]
for i in leafs:
if way_a[i] > way_b[i]:
res = max(res, way_a[i])
print(res * 2)
``` | instruction | 0 | 465 | 13 | 930 |
Yes | output | 1 | 465 | 13 | 931 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.
Alice starts at vertex 1 and Bob starts at vertex x (x ≠ 1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.
The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.
You should write a program which will determine how many moves will the game last.
Input
The first line contains two integer numbers n and x (2 ≤ n ≤ 2·105, 2 ≤ x ≤ n).
Each of the next n - 1 lines contains two integer numbers a and b (1 ≤ a, b ≤ n) — edges of the tree. It is guaranteed that the edges form a valid tree.
Output
Print the total number of moves Alice and Bob will make.
Examples
Input
4 3
1 2
2 3
2 4
Output
4
Input
5 2
1 2
2 3
3 4
2 5
Output
6
Note
In the first example the tree looks like this:
<image>
The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:
B: stay at vertex 3
A: go to vertex 2
B: stay at vertex 3
A: go to vertex 3
In the second example the tree looks like this:
<image>
The moves in the optimal strategy are:
B: go to vertex 3
A: go to vertex 2
B: go to vertex 4
A: go to vertex 3
B: stay at vertex 4
A: go to vertex 4
Submitted Solution:
```
def bottomm(x):
if len(dic[x])==0:
return 0
h=0
for i in dic[x]:
h= max(1+bottomm(i),h)
return h
def getheight(x,dic,ph):
if x in dic[ph]:
return 1
else:
h=0
for j in dic[ph]:
h=1+getheight(x,dic,j)
return h
n,x=map(int,input().split())
dic={}
par={}
for i in range(n):
dic[i+1]=[]
par[i+1]=[]
for _ in range(n-1):
a,b=map(int,input().split())
dic[a].append(b)
par[b]=a
pos_a=1
pos_b=x
ha=1
hb=getheight(x,dic,1)
ans=0
f=0
if hb==2:
if len(dic[pos_b])==0:
ans=4
f=1
elif f==0:
uptil=hb//2
maxh=bottomm(x)
k=0
while(uptil!=0):
node=par[pos_b]
pos_b=node
uptil-=1
k+=1
maxh=max(maxh,bottomm(node)+k)
node=x
while(k!=0):
node=par[x]
x=node
k-=1
ans=maxh+getheight(node,dic,1)+bottomm(node)+1
print(ans)
``` | instruction | 0 | 469 | 13 | 938 |
No | output | 1 | 469 | 13 | 939 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Roy and Biv have a set of n points on the infinite number line.
Each point has one of 3 colors: red, green, or blue.
Roy and Biv would like to connect all the points with some edges. Edges can be drawn between any of the two of the given points. The cost of an edge is equal to the distance between the two points it connects.
They want to do this in such a way that they will both see that all the points are connected (either directly or indirectly).
However, there is a catch: Roy cannot see the color red and Biv cannot see the color blue.
Therefore, they have to choose the edges in such a way that if all the red points are removed, the remaining blue and green points are connected (and similarly, if all the blue points are removed, the remaining red and green points are connected).
Help them compute the minimum cost way to choose edges to satisfy the above constraints.
Input
The first line will contain an integer n (1 ≤ n ≤ 300 000), the number of points.
The next n lines will contain two tokens pi and ci (pi is an integer, 1 ≤ pi ≤ 109, ci is a uppercase English letter 'R', 'G' or 'B'), denoting the position of the i-th point and the color of the i-th point. 'R' means red, 'G' denotes green, and 'B' means blue. The positions will be in strictly increasing order.
Output
Print a single integer, the minimum cost way to solve the problem.
Examples
Input
4
1 G
5 R
10 B
15 G
Output
23
Input
4
1 G
2 R
3 B
10 G
Output
12
Note
In the first sample, it is optimal to draw edges between the points (1,2), (1,4), (3,4). These have costs 4, 14, 5, respectively. | instruction | 0 | 508 | 13 | 1,016 |
Tags: graphs, greedy, implementation
Correct Solution:
```
import sys
n = int(input())
pos = []
ind = 0
inp = [s for line in sys.stdin.readlines() for s in line.split()]
color = []
costs = 0
reds = []
greens = []
blues = []
for i in range(n):
a,b = inp[ind],inp[ind+1]
ind+=2
pos.append(int(a))
color.append(b)
if b=='R':
reds.append(i)
elif b=='G':
greens.append(i)
else:
blues.append(i)
if len(greens)==0:
if len(reds)>0:
a = reds[0]
b = reds[-1]
costs += pos[b] - pos[a]
if len(blues)>0:
a = blues[0]
b = blues[-1]
costs += pos[b] - pos[a]
print(costs)
sys.exit()
first_g = greens[0]
last_g = greens[-1]
if len(blues)>0 and blues[0]<=first_g:
costs += pos[first_g] - pos[blues[0]]
if len(reds)>0 and reds[0]<=first_g:
costs += pos[first_g] - pos[reds[0]]
if len(blues)>0 and blues[-1]>= last_g:
costs += pos[blues[-1]] - pos[last_g]
if len(reds)>0 and reds[-1] >= last_g:
costs += pos[reds[-1]] - pos[last_g]
i = first_g
while True:
j = i+1
REDS = [i]
BLUES = [i]
while j<n and color[j]!='G':
if color[j]=='R':
REDS.append(j)
else:
BLUES.append(j)
j+=1
if j>=n:
break
REDS.append(j)
BLUES.append(j)
best_r = 0
for ind in range(len(REDS)-1):
a = REDS[ind]
b = REDS[ind+1]
best_r = max(best_r,pos[b]-pos[a])
best_b = 0
for ind in range(len(BLUES)-1):
a = BLUES[ind]
b = BLUES[ind+1]
best_b = max(best_b,pos[b]-pos[a])
costs += min(2*(pos[j]-pos[i]), 3*(pos[j]-pos[i])-best_r-best_b)
i = j
print(costs)
``` | output | 1 | 508 | 13 | 1,017 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Roy and Biv have a set of n points on the infinite number line.
Each point has one of 3 colors: red, green, or blue.
Roy and Biv would like to connect all the points with some edges. Edges can be drawn between any of the two of the given points. The cost of an edge is equal to the distance between the two points it connects.
They want to do this in such a way that they will both see that all the points are connected (either directly or indirectly).
However, there is a catch: Roy cannot see the color red and Biv cannot see the color blue.
Therefore, they have to choose the edges in such a way that if all the red points are removed, the remaining blue and green points are connected (and similarly, if all the blue points are removed, the remaining red and green points are connected).
Help them compute the minimum cost way to choose edges to satisfy the above constraints.
Input
The first line will contain an integer n (1 ≤ n ≤ 300 000), the number of points.
The next n lines will contain two tokens pi and ci (pi is an integer, 1 ≤ pi ≤ 109, ci is a uppercase English letter 'R', 'G' or 'B'), denoting the position of the i-th point and the color of the i-th point. 'R' means red, 'G' denotes green, and 'B' means blue. The positions will be in strictly increasing order.
Output
Print a single integer, the minimum cost way to solve the problem.
Examples
Input
4
1 G
5 R
10 B
15 G
Output
23
Input
4
1 G
2 R
3 B
10 G
Output
12
Note
In the first sample, it is optimal to draw edges between the points (1,2), (1,4), (3,4). These have costs 4, 14, 5, respectively. | instruction | 0 | 509 | 13 | 1,018 |
Tags: graphs, greedy, implementation
Correct Solution:
```
k=int(input())
t,a,b,m,n,o,d,e,s,x,y,z,l=13*[0]
for i in range(k):
c=input().split(" ")
f=int(c[0])
if c[1]=="G":
if o<1:
z=f
if t:
if m>0:
d=max(d,f-m)
if n>0:
e=max(e,f-n)
s+=min(2*(f-o),3*(f-o)-d-e)
d,e,a,b=4*[0]
m,n,o=3*[f]
t=True
l+=1
if c[1]=="R":
a+=1
if m<1:
x=f
if m>0 and t:
d=max(d,f-m)
m=f
if c[1]=="B":
b+=1
if n<1:
y=f
if n>0 and t:
e=max(e,f-n)
n=f
if l>0:
if a>0:
s+=m-o
if b>0:
s+=n-o
if x>0:
s+=z-x
if y>0:
s+=z-y
else:
s+=m-x+n-y
print(s)
``` | output | 1 | 509 | 13 | 1,019 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Roy and Biv have a set of n points on the infinite number line.
Each point has one of 3 colors: red, green, or blue.
Roy and Biv would like to connect all the points with some edges. Edges can be drawn between any of the two of the given points. The cost of an edge is equal to the distance between the two points it connects.
They want to do this in such a way that they will both see that all the points are connected (either directly or indirectly).
However, there is a catch: Roy cannot see the color red and Biv cannot see the color blue.
Therefore, they have to choose the edges in such a way that if all the red points are removed, the remaining blue and green points are connected (and similarly, if all the blue points are removed, the remaining red and green points are connected).
Help them compute the minimum cost way to choose edges to satisfy the above constraints.
Input
The first line will contain an integer n (1 ≤ n ≤ 300 000), the number of points.
The next n lines will contain two tokens pi and ci (pi is an integer, 1 ≤ pi ≤ 109, ci is a uppercase English letter 'R', 'G' or 'B'), denoting the position of the i-th point and the color of the i-th point. 'R' means red, 'G' denotes green, and 'B' means blue. The positions will be in strictly increasing order.
Output
Print a single integer, the minimum cost way to solve the problem.
Examples
Input
4
1 G
5 R
10 B
15 G
Output
23
Input
4
1 G
2 R
3 B
10 G
Output
12
Note
In the first sample, it is optimal to draw edges between the points (1,2), (1,4), (3,4). These have costs 4, 14, 5, respectively. | instruction | 0 | 510 | 13 | 1,020 |
Tags: graphs, greedy, implementation
Correct Solution:
```
from sys import exit, stdin, stdout
input, print = stdin.readline, stdout.write
n = int(input())
r, g, b = [], [], []
ans = 0
for i in range(n):
x, t = [i for i in input().split()]
x = int(x)
if t == 'G':
g.append(x)
elif t == 'R':
r.append(x)
else:
b.append(x)
if len(g) == 0:
if len(r):
ans += r[-1] - r[0]
if len(b):
ans += b[-1] - b[0]
print(str(ans))
exit(0)
if not len(r):
r.append(g[0])
if not len(b):
b.append(g[0])
if r[0] < g[0]:
ans += g[0] - r[0]
if b[0] < g[0]:
ans += g[0] - b[0]
if r[-1] > g[-1]:
ans += r[-1] - g[-1]
if b[-1] > g[-1]:
ans += b[-1] - g[-1]
bi, ri = 0, 0
for i in range(len(g) - 1):
while bi < len(b) - 1 and b[bi] < g[i]:
bi += 1
while ri < len(r) - 1 and r[ri] < g[i]:
ri += 1
a1, a2 = (g[i + 1] - g[i]) * 3, (g[i + 1] - g[i]) * 2
mr, mb, cbi, cri = r[ri] - g[i], b[bi] - g[i], bi, ri
while cbi + 1 < len(b) and b[cbi + 1] < g[i + 1]:
mb = max(mb, b[cbi + 1] - b[cbi])
cbi += 1
mb = max(mb, g[i + 1] - b[cbi])
while cri + 1 < len(r) and r[cri + 1] < g[i + 1]:
mr = max(mr, r[cri + 1] - r[cri])
cri += 1
mr = max(mr, g[i + 1] - r[cri])
if b[bi] < g[i] or b[bi] > g[i + 1]:
a2 = 100000000000000
a1 -= g[i + 1] - g[i]
mb = 0
if r[ri] < g[i] or r[ri] > g[i + 1]:
a2 = 100000000000000
a1 -= g[i + 1] - g[i]
mr = 0
ans += min(a1 - mr - mb, a2)
print(str(ans))
``` | output | 1 | 510 | 13 | 1,021 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Roy and Biv have a set of n points on the infinite number line.
Each point has one of 3 colors: red, green, or blue.
Roy and Biv would like to connect all the points with some edges. Edges can be drawn between any of the two of the given points. The cost of an edge is equal to the distance between the two points it connects.
They want to do this in such a way that they will both see that all the points are connected (either directly or indirectly).
However, there is a catch: Roy cannot see the color red and Biv cannot see the color blue.
Therefore, they have to choose the edges in such a way that if all the red points are removed, the remaining blue and green points are connected (and similarly, if all the blue points are removed, the remaining red and green points are connected).
Help them compute the minimum cost way to choose edges to satisfy the above constraints.
Input
The first line will contain an integer n (1 ≤ n ≤ 300 000), the number of points.
The next n lines will contain two tokens pi and ci (pi is an integer, 1 ≤ pi ≤ 109, ci is a uppercase English letter 'R', 'G' or 'B'), denoting the position of the i-th point and the color of the i-th point. 'R' means red, 'G' denotes green, and 'B' means blue. The positions will be in strictly increasing order.
Output
Print a single integer, the minimum cost way to solve the problem.
Examples
Input
4
1 G
5 R
10 B
15 G
Output
23
Input
4
1 G
2 R
3 B
10 G
Output
12
Note
In the first sample, it is optimal to draw edges between the points (1,2), (1,4), (3,4). These have costs 4, 14, 5, respectively. | instruction | 0 | 511 | 13 | 1,022 |
Tags: graphs, greedy, implementation
Correct Solution:
```
k=int(input())
t,a,b,m,n,o,d,e,s,x,y,z,l=13*[0]
for i in range(k):
c=input().split(" ")
f=int(c[0])
if c[1]=="G":
if o<1:
z=f
if t:
if m>0:
d=max(d,f-m)
if n>0:
e=max(e,f-n)
s+=min(2*(f-o),3*(f-o)-d-e)
d,e,a,b=4*[0]
m,n,o=3*[f]
t=1
l+=1
if c[1]=="R":
a+=1
if m<1:
x=f
if m>0 and t:
d=max(d,f-m)
m=f
if c[1]=="B":
b+=1
if n<1:
y=f
if n>0 and t:
e=max(e,f-n)
n=f
if l>0:
if a>0:
s+=m-o
if b>0:
s+=n-o
if x>0:
s+=z-x
if y>0:
s+=z-y
else:
s=m-x+n-y
print(s)
``` | output | 1 | 511 | 13 | 1,023 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Roy and Biv have a set of n points on the infinite number line.
Each point has one of 3 colors: red, green, or blue.
Roy and Biv would like to connect all the points with some edges. Edges can be drawn between any of the two of the given points. The cost of an edge is equal to the distance between the two points it connects.
They want to do this in such a way that they will both see that all the points are connected (either directly or indirectly).
However, there is a catch: Roy cannot see the color red and Biv cannot see the color blue.
Therefore, they have to choose the edges in such a way that if all the red points are removed, the remaining blue and green points are connected (and similarly, if all the blue points are removed, the remaining red and green points are connected).
Help them compute the minimum cost way to choose edges to satisfy the above constraints.
Input
The first line will contain an integer n (1 ≤ n ≤ 300 000), the number of points.
The next n lines will contain two tokens pi and ci (pi is an integer, 1 ≤ pi ≤ 109, ci is a uppercase English letter 'R', 'G' or 'B'), denoting the position of the i-th point and the color of the i-th point. 'R' means red, 'G' denotes green, and 'B' means blue. The positions will be in strictly increasing order.
Output
Print a single integer, the minimum cost way to solve the problem.
Examples
Input
4
1 G
5 R
10 B
15 G
Output
23
Input
4
1 G
2 R
3 B
10 G
Output
12
Note
In the first sample, it is optimal to draw edges between the points (1,2), (1,4), (3,4). These have costs 4, 14, 5, respectively. | instruction | 0 | 512 | 13 | 1,024 |
Tags: graphs, greedy, implementation
Correct Solution:
```
n=int(input())
g=[]
r=[]
b=[]
lr=0
lb=0
lg=0
for i in range(n):
a=input().split(" ")
if a[1]=="G":
g.append(int(a[0]))
lg+=1
if a[1]=="R":
r.append(int(a[0]))
lr+=1
if a[1]=="B":
b.append(int(a[0]))
lb+=1
g=g[::-1]
r=r[::-1]
b=b[::-1]
s=0
if lg>0:
for i in range(lg+1):
if i==0:
ps=0
if lr>0:
if r[lr-1]<g[lg-1]:
ps+=g[lg-1]-r[lr-1]
while r[lr-1]<g[lg-1]:
lr-=1
if lr==0:
break
if lb>0:
if b[lb-1]<g[lg-1]:
ps+=g[lg-1]-b[lb-1]
while b[lb-1]<g[lg-1]:
lb-=1
if lb==0:
break
s+=ps
elif i==lg:
ps=0
if lr>0:
ps+=r[0]-g[0]
if lb>0:
ps+=b[0]-g[0]
s+=ps
else:
ps=0
d=g[lg-i-1]-g[lg-i]
rin=False
blin=False
if lr>0:
if r[lr-1]<g[lg-i-1]:
rin=True
mdr=r[lr-1]-g[lg-i]
if lr>1:
while r[lr-2]<g[lg-i-1]:
mdr=max(mdr,r[lr-2]-r[lr-1])
lr-=1
if lr==1:
break
mdr=max(mdr,g[lg-i-1]-r[lr-1])
lr-=1
if lb>0:
if b[lb-1]<g[lg-i-1]:
blin=True
mdb=b[lb-1]-g[lg-i]
if lb>1:
while b[lb-2]<g[lg-i-1]:
mdb=max(mdb,b[lb-2]-b[lb-1])
lb-=1
if lb==1:
break
mdb=max(mdb,g[lg-i-1]-b[lb-1])
lb-=1
if blin and rin:
ps+=min(2*d,3*d-mdr-mdb)
else:
ps+=d
if blin:
ps+=d-mdb
elif rin:
ps+=d-mdr
s+=ps
else:
if lr>0:
s+=r[0]-r[-1]
if lb>0:
s+=b[0]-b[-1]
print(s)
``` | output | 1 | 512 | 13 | 1,025 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Roy and Biv have a set of n points on the infinite number line.
Each point has one of 3 colors: red, green, or blue.
Roy and Biv would like to connect all the points with some edges. Edges can be drawn between any of the two of the given points. The cost of an edge is equal to the distance between the two points it connects.
They want to do this in such a way that they will both see that all the points are connected (either directly or indirectly).
However, there is a catch: Roy cannot see the color red and Biv cannot see the color blue.
Therefore, they have to choose the edges in such a way that if all the red points are removed, the remaining blue and green points are connected (and similarly, if all the blue points are removed, the remaining red and green points are connected).
Help them compute the minimum cost way to choose edges to satisfy the above constraints.
Input
The first line will contain an integer n (1 ≤ n ≤ 300 000), the number of points.
The next n lines will contain two tokens pi and ci (pi is an integer, 1 ≤ pi ≤ 109, ci is a uppercase English letter 'R', 'G' or 'B'), denoting the position of the i-th point and the color of the i-th point. 'R' means red, 'G' denotes green, and 'B' means blue. The positions will be in strictly increasing order.
Output
Print a single integer, the minimum cost way to solve the problem.
Examples
Input
4
1 G
5 R
10 B
15 G
Output
23
Input
4
1 G
2 R
3 B
10 G
Output
12
Note
In the first sample, it is optimal to draw edges between the points (1,2), (1,4), (3,4). These have costs 4, 14, 5, respectively. | instruction | 0 | 513 | 13 | 1,026 |
Tags: graphs, greedy, implementation
Correct Solution:
```
n = int( input() )
min_red, max_red = -1, -1
min_blue, max_blue = -1, -1
left_green, right_green = -1, -1
a = []
ans = 0
last_r, last_b, last_g = -1, -1, -1
r_edges = []
b_edges = []
g_edges = []
for i in range( n ):
p, c = input().split()
p = int(p)
if c == 'R' or c == 'G':
if last_r != -1:
r_edges.append( p - last_r )
last_r = p
if c == 'B' or c == 'G':
if last_b != -1:
b_edges.append( p - last_b )
last_b = p
if c == 'G':
ans += sum(r_edges) + sum(b_edges)
if len(r_edges) > 0:
max_red = max(r_edges)
if len(b_edges) > 0:
max_blue = max(b_edges)
if last_g != -1:
if (p-last_g) < (max_red+max_blue):
ans += (p-last_g)
ans -= (max_red+max_blue)
r_edges = [ ]
b_edges = [ ]
last_g = p
ans += sum(r_edges) + sum(b_edges)
print( ans )
``` | output | 1 | 513 | 13 | 1,027 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Roy and Biv have a set of n points on the infinite number line.
Each point has one of 3 colors: red, green, or blue.
Roy and Biv would like to connect all the points with some edges. Edges can be drawn between any of the two of the given points. The cost of an edge is equal to the distance between the two points it connects.
They want to do this in such a way that they will both see that all the points are connected (either directly or indirectly).
However, there is a catch: Roy cannot see the color red and Biv cannot see the color blue.
Therefore, they have to choose the edges in such a way that if all the red points are removed, the remaining blue and green points are connected (and similarly, if all the blue points are removed, the remaining red and green points are connected).
Help them compute the minimum cost way to choose edges to satisfy the above constraints.
Input
The first line will contain an integer n (1 ≤ n ≤ 300 000), the number of points.
The next n lines will contain two tokens pi and ci (pi is an integer, 1 ≤ pi ≤ 109, ci is a uppercase English letter 'R', 'G' or 'B'), denoting the position of the i-th point and the color of the i-th point. 'R' means red, 'G' denotes green, and 'B' means blue. The positions will be in strictly increasing order.
Output
Print a single integer, the minimum cost way to solve the problem.
Examples
Input
4
1 G
5 R
10 B
15 G
Output
23
Input
4
1 G
2 R
3 B
10 G
Output
12
Note
In the first sample, it is optimal to draw edges between the points (1,2), (1,4), (3,4). These have costs 4, 14, 5, respectively. | instruction | 0 | 514 | 13 | 1,028 |
Tags: graphs, greedy, implementation
Correct Solution:
```
#! /usr/bin/env python3
#------------------------------------------------
# Author: krishna
# Created: Fri Dec 29 23:04:38 IST 2017
# File Name: f.py
# USAGE:
# f.py
# Description:
#
#------------------------------------------------
import sys
n = int(sys.stdin.readline().rstrip())
locations = {
'R' : [],
'G' : [],
'B' : []
}
for i in range(n):
(x, c) = sys.stdin.readline().rstrip().split()
locations[c].append(int(x))
# for c in locations.keys():
# locations[c].sort()
def solve(locations):
count = 0
rPtr = 0
bPtr = 0
gPtr = 0
if (len(locations['G']) == 0):
if (len(locations['R'])):
count += locations['R'][-1] - locations['R'][0]
if (len(locations['B'])):
count += locations['B'][-1] - locations['B'][0]
return count
while (len(locations['G']) > gPtr):
# Eat predecessors
if (
(len(locations['R']) > rPtr)
and (locations['G'][gPtr] > locations['R'][rPtr])
):
count += locations['G'][gPtr] - locations['R'][rPtr]
while (
(len(locations['R']) > rPtr)
and (locations['G'][gPtr] > locations['R'][rPtr])
):
rPtr += 1
# Eat predecessors
if (
(len(locations['B']) > bPtr)
and (locations['G'][gPtr] > locations['B'][bPtr])
):
count += locations['G'][gPtr] - locations['B'][bPtr]
while (
(len(locations['B']) > bPtr)
and (locations['G'][gPtr] > locations['B'][bPtr])
):
bPtr += 1
# Eat last successors
if (len(locations['G']) == (gPtr + 1)):
if (len(locations['R']) > rPtr):
count += locations['R'][-1] - locations['G'][gPtr]
if (len(locations['B']) > bPtr):
count += locations['B'][-1] - locations['G'][gPtr]
return count
# Calc intervels
if (len(locations['G']) > (gPtr + 1)):
prevR = locations['G'][gPtr]
maxRd = 0
while (len(locations['R']) > rPtr):
if (locations['R'][rPtr] < locations['G'][gPtr + 1]):
maxRd = max(maxRd, locations['R'][rPtr] - prevR)
prevR = locations['R'][rPtr]
rPtr += 1
else:
break
maxRd = max(maxRd, locations['G'][gPtr + 1] - prevR)
prevB = locations['G'][gPtr]
maxBd = 0
while (len(locations['B']) > bPtr):
if (locations['B'][bPtr] < locations['G'][gPtr + 1]):
maxBd = max(maxBd, locations['B'][bPtr] - prevB)
prevB = locations['B'][bPtr]
bPtr += 1
else:
break
maxBd = max(maxBd, locations['G'][gPtr + 1] - prevB)
count += min(
2 * (locations['G'][gPtr + 1] - locations['G'][gPtr]),
(3 * (locations['G'][gPtr + 1] - locations['G'][gPtr])) - maxRd - maxBd
)
gPtr += 1
return count
print(solve(locations))
``` | output | 1 | 514 | 13 | 1,029 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Roy and Biv have a set of n points on the infinite number line.
Each point has one of 3 colors: red, green, or blue.
Roy and Biv would like to connect all the points with some edges. Edges can be drawn between any of the two of the given points. The cost of an edge is equal to the distance between the two points it connects.
They want to do this in such a way that they will both see that all the points are connected (either directly or indirectly).
However, there is a catch: Roy cannot see the color red and Biv cannot see the color blue.
Therefore, they have to choose the edges in such a way that if all the red points are removed, the remaining blue and green points are connected (and similarly, if all the blue points are removed, the remaining red and green points are connected).
Help them compute the minimum cost way to choose edges to satisfy the above constraints.
Input
The first line will contain an integer n (1 ≤ n ≤ 300 000), the number of points.
The next n lines will contain two tokens pi and ci (pi is an integer, 1 ≤ pi ≤ 109, ci is a uppercase English letter 'R', 'G' or 'B'), denoting the position of the i-th point and the color of the i-th point. 'R' means red, 'G' denotes green, and 'B' means blue. The positions will be in strictly increasing order.
Output
Print a single integer, the minimum cost way to solve the problem.
Examples
Input
4
1 G
5 R
10 B
15 G
Output
23
Input
4
1 G
2 R
3 B
10 G
Output
12
Note
In the first sample, it is optimal to draw edges between the points (1,2), (1,4), (3,4). These have costs 4, 14, 5, respectively. | instruction | 0 | 515 | 13 | 1,030 |
Tags: graphs, greedy, implementation
Correct Solution:
```
n=int(input())
nfirst,rc,bc,memr,memb,memg,dr,db,s,rl,bl,gl,lg=13*[0]
for i in range(n):
a=input().split(" ")
if a[1]=="G":
if memg==0:
gl=int(a[0])
if nfirst:
if memr>0:
dr=max(dr,int(a[0])-memr)
if memb>0:
db=max(db,int(a[0])-memb)
s+=min(2*(int(a[0])-memg),3*(int(a[0])-memg)-dr-db)
dr,db,rc,bc=4*[0]
memr,memb,memg=3*[int(a[0])]
nfirst=True
lg+=1
elif a[1]=="R":
rc+=1
if memr==0:
rl=int(a[0])
if memr>0 and nfirst:
dr=max(dr,int(a[0])-memr)
memr=int(a[0])
elif a[1]=="B":
bc+=1
if memb==0:
bl=int(a[0])
if memb>0 and nfirst:
db=max(db,int(a[0])-memb)
memb=int(a[0])
if lg>0:
if rc>0:
s+=memr-memg
if bc>0:
s+=memb-memg
if rl>0:
s+=gl-rl
if bl>0:
s+=gl-bl
else:
s+=memr-rl+memb-bl
print(s)
``` | output | 1 | 515 | 13 | 1,031 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a string s of length n. Does a tree with n vertices that satisfies the following conditions exist?
* The vertices are numbered 1,2,..., n.
* The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i.
* If the i-th character in s is `1`, we can have a connected component of size i by removing one edge from the tree.
* If the i-th character in s is `0`, we cannot have a connected component of size i by removing any one edge from the tree.
If such a tree exists, construct one such tree.
Constraints
* 2 \leq n \leq 10^5
* s is a string of length n consisting of `0` and `1`.
Input
Input is given from Standard Input in the following format:
s
Output
If a tree with n vertices that satisfies the conditions does not exist, print `-1`.
If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted.
Examples
Input
1111
Output
-1
Input
1110
Output
1 2
2 3
3 4
Input
1010
Output
1 2
1 3
1 4 | instruction | 0 | 591 | 13 | 1,182 |
"Correct Solution:
```
s=input()
if s[0]=='0' or s[-1]=='1' or s[:-1]!=s[:-1][::-1]:
print(-1)
exit(0)
e=[]
bi=0
for i,j in enumerate(s[:-1]):
e.append([bi,i+1])
if j=='1':
bi=i+1
for i,j in e:
print(i+1,j+1)
``` | output | 1 | 591 | 13 | 1,183 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a string s of length n. Does a tree with n vertices that satisfies the following conditions exist?
* The vertices are numbered 1,2,..., n.
* The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i.
* If the i-th character in s is `1`, we can have a connected component of size i by removing one edge from the tree.
* If the i-th character in s is `0`, we cannot have a connected component of size i by removing any one edge from the tree.
If such a tree exists, construct one such tree.
Constraints
* 2 \leq n \leq 10^5
* s is a string of length n consisting of `0` and `1`.
Input
Input is given from Standard Input in the following format:
s
Output
If a tree with n vertices that satisfies the conditions does not exist, print `-1`.
If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted.
Examples
Input
1111
Output
-1
Input
1110
Output
1 2
2 3
3 4
Input
1010
Output
1 2
1 3
1 4 | instruction | 0 | 592 | 13 | 1,184 |
"Correct Solution:
```
s = input()
n,m,m2 = len(s),1,2
if 1-int(s[0]) or int(s[-1]) or any(s[i]!=s[n-i-2] for i in range(n-1)): print(-1)
else:
for i in range(n-1):
print(m,m2)
if int(s[i]): m = m2
m2+=1
``` | output | 1 | 592 | 13 | 1,185 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a string s of length n. Does a tree with n vertices that satisfies the following conditions exist?
* The vertices are numbered 1,2,..., n.
* The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i.
* If the i-th character in s is `1`, we can have a connected component of size i by removing one edge from the tree.
* If the i-th character in s is `0`, we cannot have a connected component of size i by removing any one edge from the tree.
If such a tree exists, construct one such tree.
Constraints
* 2 \leq n \leq 10^5
* s is a string of length n consisting of `0` and `1`.
Input
Input is given from Standard Input in the following format:
s
Output
If a tree with n vertices that satisfies the conditions does not exist, print `-1`.
If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted.
Examples
Input
1111
Output
-1
Input
1110
Output
1 2
2 3
3 4
Input
1010
Output
1 2
1 3
1 4 | instruction | 0 | 593 | 13 | 1,186 |
"Correct Solution:
```
#01:36
s = input()
n = len(s)
if s[-1] == '1':
print(-1)
exit()
t = s[:-1]
if t[::-1] != t:
print(-1)
exit()
if s[0] == '0':
print(-1)
exit()
print(0+1,1+1)
now = 0
for i in range(2,n):
print(now+1,i+1)
if s[i-1] == '1':
now = i
``` | output | 1 | 593 | 13 | 1,187 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a string s of length n. Does a tree with n vertices that satisfies the following conditions exist?
* The vertices are numbered 1,2,..., n.
* The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i.
* If the i-th character in s is `1`, we can have a connected component of size i by removing one edge from the tree.
* If the i-th character in s is `0`, we cannot have a connected component of size i by removing any one edge from the tree.
If such a tree exists, construct one such tree.
Constraints
* 2 \leq n \leq 10^5
* s is a string of length n consisting of `0` and `1`.
Input
Input is given from Standard Input in the following format:
s
Output
If a tree with n vertices that satisfies the conditions does not exist, print `-1`.
If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted.
Examples
Input
1111
Output
-1
Input
1110
Output
1 2
2 3
3 4
Input
1010
Output
1 2
1 3
1 4 | instruction | 0 | 594 | 13 | 1,188 |
"Correct Solution:
```
x = [c for c in input()]
n = len(x)
ret=[]
for i in range(n-1):
ret.append([0,0])
if x[n-1] == "1":
print (-1)
elif x[0] == "0":
print (-1)
else:
flg = 1
for i in range(n-1):
if x[i] != x[n-1-i-1]:
flg = 0
if flg == 0:
print (-1)
else:
a=1
for i in range(n-1):
if x[i] == "1":
ret[i] = [a,i+2]
a=i+2
else:
ret[i] = [a,i+2]
for i in range(n-1):
print ("{0} {1}".format(ret[i][0], ret[i][1]))
``` | output | 1 | 594 | 13 | 1,189 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a string s of length n. Does a tree with n vertices that satisfies the following conditions exist?
* The vertices are numbered 1,2,..., n.
* The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i.
* If the i-th character in s is `1`, we can have a connected component of size i by removing one edge from the tree.
* If the i-th character in s is `0`, we cannot have a connected component of size i by removing any one edge from the tree.
If such a tree exists, construct one such tree.
Constraints
* 2 \leq n \leq 10^5
* s is a string of length n consisting of `0` and `1`.
Input
Input is given from Standard Input in the following format:
s
Output
If a tree with n vertices that satisfies the conditions does not exist, print `-1`.
If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted.
Examples
Input
1111
Output
-1
Input
1110
Output
1 2
2 3
3 4
Input
1010
Output
1 2
1 3
1 4 | instruction | 0 | 595 | 13 | 1,190 |
"Correct Solution:
```
import sys
import math
from collections import defaultdict
from bisect import bisect_left, bisect_right
sys.setrecursionlimit(10**7)
def input():
return sys.stdin.readline()[:-1]
mod = 10**9 + 7
def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
if row <= 0:
return [[] for _ in range(col)]
elif col == 1:
return [I() for _ in range(row)]
else:
read_all = [LI() for _ in range(row)]
return map(list, zip(*read_all))
#################
s = list(input())
n = len(s)
for i in range((n-1)//2+1):
if s[i] != s[n-2-i]:
print(-1)
exit()
if s[0] == '0':
print(-1)
exit()
if s[n-1] == '1':
print(-1)
exit()
from_ = 1
to_ = 2
ans = []
for i in range(n-1):
ans.append((from_,to_))
if s[i] == '1':
from_ = to_
to_ += 1
else:
to_ += 1
for a in ans:
print(*a)
``` | output | 1 | 595 | 13 | 1,191 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a string s of length n. Does a tree with n vertices that satisfies the following conditions exist?
* The vertices are numbered 1,2,..., n.
* The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i.
* If the i-th character in s is `1`, we can have a connected component of size i by removing one edge from the tree.
* If the i-th character in s is `0`, we cannot have a connected component of size i by removing any one edge from the tree.
If such a tree exists, construct one such tree.
Constraints
* 2 \leq n \leq 10^5
* s is a string of length n consisting of `0` and `1`.
Input
Input is given from Standard Input in the following format:
s
Output
If a tree with n vertices that satisfies the conditions does not exist, print `-1`.
If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted.
Examples
Input
1111
Output
-1
Input
1110
Output
1 2
2 3
3 4
Input
1010
Output
1 2
1 3
1 4 | instruction | 0 | 596 | 13 | 1,192 |
"Correct Solution:
```
s = input()
n = len(s)
if s[n - 1] == '1' or s[0] == '0':
print(-1)
exit()
for i in range(n):
if s[i] != s[n - i - 2]:
print(-1)
exit()
cur_s = 2
cur_p = 2
print(1, 2)
for i in range(n - 2):
if s[i + 1] == '1':
print(cur_s + 1, cur_p)
cur_p = cur_s + 1
else:
print(cur_s + 1, cur_p)
cur_s += 1
``` | output | 1 | 596 | 13 | 1,193 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a string s of length n. Does a tree with n vertices that satisfies the following conditions exist?
* The vertices are numbered 1,2,..., n.
* The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i.
* If the i-th character in s is `1`, we can have a connected component of size i by removing one edge from the tree.
* If the i-th character in s is `0`, we cannot have a connected component of size i by removing any one edge from the tree.
If such a tree exists, construct one such tree.
Constraints
* 2 \leq n \leq 10^5
* s is a string of length n consisting of `0` and `1`.
Input
Input is given from Standard Input in the following format:
s
Output
If a tree with n vertices that satisfies the conditions does not exist, print `-1`.
If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted.
Examples
Input
1111
Output
-1
Input
1110
Output
1 2
2 3
3 4
Input
1010
Output
1 2
1 3
1 4 | instruction | 0 | 597 | 13 | 1,194 |
"Correct Solution:
```
s = input()
if s[0] == '0' or s[-1] == '1' or s[:-1] != s[:-1][::-1]:
print(-1)
exit(0)
edges = []
head = 0
for idx, i in enumerate(s[:-1]):
edges.append([head, idx + 1])
if i == '1':
head = idx + 1
for i, j in edges:
print(i + 1, j + 1)
``` | output | 1 | 597 | 13 | 1,195 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a string s of length n. Does a tree with n vertices that satisfies the following conditions exist?
* The vertices are numbered 1,2,..., n.
* The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i.
* If the i-th character in s is `1`, we can have a connected component of size i by removing one edge from the tree.
* If the i-th character in s is `0`, we cannot have a connected component of size i by removing any one edge from the tree.
If such a tree exists, construct one such tree.
Constraints
* 2 \leq n \leq 10^5
* s is a string of length n consisting of `0` and `1`.
Input
Input is given from Standard Input in the following format:
s
Output
If a tree with n vertices that satisfies the conditions does not exist, print `-1`.
If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted.
Examples
Input
1111
Output
-1
Input
1110
Output
1 2
2 3
3 4
Input
1010
Output
1 2
1 3
1 4 | instruction | 0 | 598 | 13 | 1,196 |
"Correct Solution:
```
s = input()
l = len(s)
if s[0] != '1' or s[-2] != '1' or s[-1] != '0':
print('-1')
exit()
if s[:-1] != s[:-1][::-1]:
print('-1')
exit()
# 1頂点に全部ついた状態から始める
e = [l] + [-1] * (l-1)
now = 0
h = (l-1) // 2
for i in range(h, 0, -1):
c = s[i]
if c == '0':
continue
# now の木から子をi個取り出して繋げる
e[now] = l - i
e[l-i-1] = l
now = l-i-1
for i, a in enumerate(e):
for j in range(i+2, a+1):
print(i+1, j)
``` | output | 1 | 598 | 13 | 1,197 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s of length n. Does a tree with n vertices that satisfies the following conditions exist?
* The vertices are numbered 1,2,..., n.
* The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i.
* If the i-th character in s is `1`, we can have a connected component of size i by removing one edge from the tree.
* If the i-th character in s is `0`, we cannot have a connected component of size i by removing any one edge from the tree.
If such a tree exists, construct one such tree.
Constraints
* 2 \leq n \leq 10^5
* s is a string of length n consisting of `0` and `1`.
Input
Input is given from Standard Input in the following format:
s
Output
If a tree with n vertices that satisfies the conditions does not exist, print `-1`.
If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted.
Examples
Input
1111
Output
-1
Input
1110
Output
1 2
2 3
3 4
Input
1010
Output
1 2
1 3
1 4
Submitted Solution:
```
def no():
print(-1)
exit()
s = input()
n = len(s)
if s[-1] == "1":
no()
s = s[:-1]
if s != s[::-1]:
no()
if s[0] == "0":
no()
li = [0]
adj = [[] for _ in range(n + 1)]
for v, e in enumerate(s, 1):
if e == "1":
for u in li:
adj[u].append(v)
li = []
li.append(v)
adj[n-1].append(n)
for u, vs in enumerate(adj[1:], 1):
for v in vs:
print(u, v)
``` | instruction | 0 | 599 | 13 | 1,198 |
Yes | output | 1 | 599 | 13 | 1,199 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s of length n. Does a tree with n vertices that satisfies the following conditions exist?
* The vertices are numbered 1,2,..., n.
* The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i.
* If the i-th character in s is `1`, we can have a connected component of size i by removing one edge from the tree.
* If the i-th character in s is `0`, we cannot have a connected component of size i by removing any one edge from the tree.
If such a tree exists, construct one such tree.
Constraints
* 2 \leq n \leq 10^5
* s is a string of length n consisting of `0` and `1`.
Input
Input is given from Standard Input in the following format:
s
Output
If a tree with n vertices that satisfies the conditions does not exist, print `-1`.
If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted.
Examples
Input
1111
Output
-1
Input
1110
Output
1 2
2 3
3 4
Input
1010
Output
1 2
1 3
1 4
Submitted Solution:
```
s = input()
n = len(s)
ok = s[0] == '1' and s[n-1] == '0'
for i in range(n-1):
ok = ok and s[i] == s[n-2-i]
if not ok:
print(-1)
exit()
s2 = s[:n//2]
i = s2.rindex('1')
for k in range(i, n-1):
print(n, k+1)
while i > 0:
j = i - 1
while s[j] != '1':
j -= 1
for k in range(j, i):
print(i+1, k+1)
i = j
``` | instruction | 0 | 600 | 13 | 1,200 |
Yes | output | 1 | 600 | 13 | 1,201 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s of length n. Does a tree with n vertices that satisfies the following conditions exist?
* The vertices are numbered 1,2,..., n.
* The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i.
* If the i-th character in s is `1`, we can have a connected component of size i by removing one edge from the tree.
* If the i-th character in s is `0`, we cannot have a connected component of size i by removing any one edge from the tree.
If such a tree exists, construct one such tree.
Constraints
* 2 \leq n \leq 10^5
* s is a string of length n consisting of `0` and `1`.
Input
Input is given from Standard Input in the following format:
s
Output
If a tree with n vertices that satisfies the conditions does not exist, print `-1`.
If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted.
Examples
Input
1111
Output
-1
Input
1110
Output
1 2
2 3
3 4
Input
1010
Output
1 2
1 3
1 4
Submitted Solution:
```
import sys
input = sys.stdin.readline
s = list(map(int, list(input())[: -1]))
if s[0] == 0 or s[-1] == 1:
print(-1)
exit(0)
n = len(s)
for i in range(n - 1):
if s[i] != s[-2 - i]:
print(-1)
exit(0)
res = []
temp = []
s[-1] = 1
for i in range(n):
if s[i] == 0 or i == 0:
temp.append(i + 1)
else:
if len(res):
p = res[-1][0]
res.append((i + 1, p))
if len(temp):
while len(temp):
res.append((i + 1, temp.pop()))
for _ in range(len(res)):
print(*res.pop())
``` | instruction | 0 | 601 | 13 | 1,202 |
Yes | output | 1 | 601 | 13 | 1,203 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s of length n. Does a tree with n vertices that satisfies the following conditions exist?
* The vertices are numbered 1,2,..., n.
* The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i.
* If the i-th character in s is `1`, we can have a connected component of size i by removing one edge from the tree.
* If the i-th character in s is `0`, we cannot have a connected component of size i by removing any one edge from the tree.
If such a tree exists, construct one such tree.
Constraints
* 2 \leq n \leq 10^5
* s is a string of length n consisting of `0` and `1`.
Input
Input is given from Standard Input in the following format:
s
Output
If a tree with n vertices that satisfies the conditions does not exist, print `-1`.
If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted.
Examples
Input
1111
Output
-1
Input
1110
Output
1 2
2 3
3 4
Input
1010
Output
1 2
1 3
1 4
Submitted Solution:
```
s=input()
n=len(s)
def check():
if s[0]=="0" or s[-1] =="1":
return False
for i in range(n):
if s[i] != s[n-i-2]:
return False
return True
if not check():
print(-1)
exit()
now=1
for i in range(n-1):
print(now,i+2)
if s[i]=="1":
now=i+2
``` | instruction | 0 | 602 | 13 | 1,204 |
Yes | output | 1 | 602 | 13 | 1,205 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s of length n. Does a tree with n vertices that satisfies the following conditions exist?
* The vertices are numbered 1,2,..., n.
* The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i.
* If the i-th character in s is `1`, we can have a connected component of size i by removing one edge from the tree.
* If the i-th character in s is `0`, we cannot have a connected component of size i by removing any one edge from the tree.
If such a tree exists, construct one such tree.
Constraints
* 2 \leq n \leq 10^5
* s is a string of length n consisting of `0` and `1`.
Input
Input is given from Standard Input in the following format:
s
Output
If a tree with n vertices that satisfies the conditions does not exist, print `-1`.
If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted.
Examples
Input
1111
Output
-1
Input
1110
Output
1 2
2 3
3 4
Input
1010
Output
1 2
1 3
1 4
Submitted Solution:
```
s = input()
if s[0]=='0' or s[-1]=='1':
print(-1)
exit()
for i in range(len(s)//2):
if s[i]=='1' and s[-i-2]=='0':
print(-1)
exit()
par = len(s)
for i in range(len(s)-2,-1,-1):
if s[i]=='1':
print(i+1,par)
par = i+1
else:
print(i+1,par)
``` | instruction | 0 | 603 | 13 | 1,206 |
No | output | 1 | 603 | 13 | 1,207 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s of length n. Does a tree with n vertices that satisfies the following conditions exist?
* The vertices are numbered 1,2,..., n.
* The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i.
* If the i-th character in s is `1`, we can have a connected component of size i by removing one edge from the tree.
* If the i-th character in s is `0`, we cannot have a connected component of size i by removing any one edge from the tree.
If such a tree exists, construct one such tree.
Constraints
* 2 \leq n \leq 10^5
* s is a string of length n consisting of `0` and `1`.
Input
Input is given from Standard Input in the following format:
s
Output
If a tree with n vertices that satisfies the conditions does not exist, print `-1`.
If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted.
Examples
Input
1111
Output
-1
Input
1110
Output
1 2
2 3
3 4
Input
1010
Output
1 2
1 3
1 4
Submitted Solution:
```
import sys
sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))
S = list(sr())
N = len(S)
if S[-1] == '1' or S[0] == '0':
print(-1); exit()
S = ['-'] + S
def solve(S):
prev = 1
graph = []
for i in range(1, N//2 + 1):
if S[i] != S[N-i]:
print(-1); exit()
if S[i] == '0':
continue
for x in range(prev, i):
print(x, i)
prev = i
for x in range(prev, N):
print(x, N)
graph = solve(S)
``` | instruction | 0 | 604 | 13 | 1,208 |
No | output | 1 | 604 | 13 | 1,209 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s of length n. Does a tree with n vertices that satisfies the following conditions exist?
* The vertices are numbered 1,2,..., n.
* The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i.
* If the i-th character in s is `1`, we can have a connected component of size i by removing one edge from the tree.
* If the i-th character in s is `0`, we cannot have a connected component of size i by removing any one edge from the tree.
If such a tree exists, construct one such tree.
Constraints
* 2 \leq n \leq 10^5
* s is a string of length n consisting of `0` and `1`.
Input
Input is given from Standard Input in the following format:
s
Output
If a tree with n vertices that satisfies the conditions does not exist, print `-1`.
If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted.
Examples
Input
1111
Output
-1
Input
1110
Output
1 2
2 3
3 4
Input
1010
Output
1 2
1 3
1 4
Submitted Solution:
```
#!/usr/bin/python3
import math
import sys
DEBUG = False
def inp():
return sys.stdin.readline().rstrip()
def dprint(*value, sep=' ', end='\n'):
if DEBUG:
print(*value, sep=sep, end=end)
def solve(S):
N = len(S)
if S[0] == '0' or S[-1] == '1':
return None
for i in range((N - 1) // 2):
if S[i] != S[-2 - i]:
return None
mxsz = 1
for i in range((N - 2) // 2):
if S[i] == '0' and S[i + 1] == '1':
return None
if S[i + 1] == '1':
mxsz = i + 2
G = []
# print(mxsz)
for i in range(2, mxsz + 2):
G.append((i - 1, i))
for i in range(mxsz + 2, N + 1):
G.append((1, i))
return G
def main():
ans = solve(inp())
if ans is None:
print('-1')
return
for (p, q) in ans:
print(p, q)
if __name__ == '__main__':
main()
``` | instruction | 0 | 605 | 13 | 1,210 |
No | output | 1 | 605 | 13 | 1,211 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s of length n. Does a tree with n vertices that satisfies the following conditions exist?
* The vertices are numbered 1,2,..., n.
* The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i.
* If the i-th character in s is `1`, we can have a connected component of size i by removing one edge from the tree.
* If the i-th character in s is `0`, we cannot have a connected component of size i by removing any one edge from the tree.
If such a tree exists, construct one such tree.
Constraints
* 2 \leq n \leq 10^5
* s is a string of length n consisting of `0` and `1`.
Input
Input is given from Standard Input in the following format:
s
Output
If a tree with n vertices that satisfies the conditions does not exist, print `-1`.
If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted.
Examples
Input
1111
Output
-1
Input
1110
Output
1 2
2 3
3 4
Input
1010
Output
1 2
1 3
1 4
Submitted Solution:
```
from bisect import *
from collections import *
from fractions import gcd
from math import factorial
from itertools import *
S=input()
if S[-1]=="1" or S[0]=="0":
print(-1)
exit()
length=(len(S)-1)//2
for i in range(length):
if S[i]!=S[-2-i]:
print(-1)
exit()
odds=[]
even=[]
lst=[]
for i in range(1,length+1+(len(S)%2==0)):
if S[i-1]=="1":
if i%2==1:
odds.append(i)
else:
even.append(i)
``` | instruction | 0 | 606 | 13 | 1,212 |
No | output | 1 | 606 | 13 | 1,213 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a forest — an undirected graph with n vertices such that each its connected component is a tree.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
You task is to add some edges (possibly zero) to the graph so that it becomes a tree and the diameter of the tree is minimal possible.
If there are multiple correct answers, print any of them.
Input
The first line contains two integers n and m (1 ≤ n ≤ 1000, 0 ≤ m ≤ n - 1) — the number of vertices of the graph and the number of edges, respectively.
Each of the next m lines contains two integers v and u (1 ≤ v, u ≤ n, v ≠ u) — the descriptions of the edges.
It is guaranteed that the given graph is a forest.
Output
In the first line print the diameter of the resulting tree.
Each of the next (n - 1) - m lines should contain two integers v and u (1 ≤ v, u ≤ n, v ≠ u) — the descriptions of the added edges.
The resulting graph should be a tree and its diameter should be minimal possible.
For m = n - 1 no edges are added, thus the output consists of a single integer — diameter of the given tree.
If there are multiple correct answers, print any of them.
Examples
Input
4 2
1 2
2 3
Output
2
4 2
Input
2 0
Output
1
1 2
Input
3 2
1 3
2 3
Output
2
Note
In the first example adding edges (1, 4) or (3, 4) will lead to a total diameter of 3. Adding edge (2, 4), however, will make it 2.
Edge (1, 2) is the only option you have for the second example. The diameter is 1.
You can't add any edges in the third example. The diameter is already 2. | instruction | 0 | 836 | 13 | 1,672 |
Tags: constructive algorithms, dfs and similar, greedy, trees
Correct Solution:
```
import math
n,m=map(int,input().split())
neigh=[]
for i in range(n):
neigh.append([])
for i in range(m):
a,b=map(int,input().split())
neigh[a-1].append(b-1)
neigh[b-1].append(a-1)
seen=set()
index=[0]*n
diams=[]
trees=0
for i in range(n):
if i not in seen:
trees+=1
index[i]=trees
seen.add(i)
layer=[i]
prev=None
pars=[None]
while layer!=[]:
newlayer=[]
newpars=[]
for i in range(len(layer)):
vert=layer[i]
par=pars[i]
for child in neigh[vert]:
if child!=par:
newlayer.append(child)
newpars.append(vert)
index[child]=trees
seen.add(child)
prev=layer
layer=newlayer
pars=newpars
far=prev[0]
layer=[[far]]
pars=[None]
prev=None
while layer!=[]:
newlayer=[]
newpars=[]
for i in range(len(layer)):
vert=layer[i][-1]
par=pars[i]
for child in neigh[vert]:
if child!=par:
newlayer.append(layer[i]+[child])
newpars.append(vert)
prev=layer
layer=newlayer
pars=newpars
diam=prev[0]
lent=len(diam)
mid=diam[lent//2]
diams.append((lent-1,mid))
diams.sort(reverse=True)
poss=[diams[0][0]]
if len(diams)>1:
poss.append(math.ceil(diams[0][0]/2)+1+math.ceil(diams[1][0]/2))
if len(diams)>2:
poss.append(math.ceil(diams[1][0]/2)+2+math.ceil(diams[2][0]/2))
print(max(poss))
cent=diams[0][1]
for i in range(len(diams)-1):
print(cent+1,diams[i+1][1]+1)
``` | output | 1 | 836 | 13 | 1,673 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a forest — an undirected graph with n vertices such that each its connected component is a tree.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
You task is to add some edges (possibly zero) to the graph so that it becomes a tree and the diameter of the tree is minimal possible.
If there are multiple correct answers, print any of them.
Input
The first line contains two integers n and m (1 ≤ n ≤ 1000, 0 ≤ m ≤ n - 1) — the number of vertices of the graph and the number of edges, respectively.
Each of the next m lines contains two integers v and u (1 ≤ v, u ≤ n, v ≠ u) — the descriptions of the edges.
It is guaranteed that the given graph is a forest.
Output
In the first line print the diameter of the resulting tree.
Each of the next (n - 1) - m lines should contain two integers v and u (1 ≤ v, u ≤ n, v ≠ u) — the descriptions of the added edges.
The resulting graph should be a tree and its diameter should be minimal possible.
For m = n - 1 no edges are added, thus the output consists of a single integer — diameter of the given tree.
If there are multiple correct answers, print any of them.
Examples
Input
4 2
1 2
2 3
Output
2
4 2
Input
2 0
Output
1
1 2
Input
3 2
1 3
2 3
Output
2
Note
In the first example adding edges (1, 4) or (3, 4) will lead to a total diameter of 3. Adding edge (2, 4), however, will make it 2.
Edge (1, 2) is the only option you have for the second example. The diameter is 1.
You can't add any edges in the third example. The diameter is already 2. | instruction | 0 | 837 | 13 | 1,674 |
Tags: constructive algorithms, dfs and similar, greedy, trees
Correct Solution:
```
from collections import deque
##make the tree
n,m=[int(x) for x in input().split()]
tree={}
for i in range(m):
a,b=[int(x) for x in input().split()]
if a not in tree:
tree[a]=[b]
else:
tree[a].append(b)
if b not in tree:
tree[b]=[a]
else:
tree[b].append(a)
for i in range(1,n+1):
if i not in tree:
tree[i]=[]
def solve(node):
###bfs tree to get farthest node
from collections import deque
def bfs(graph,currnode):
visited=[False for x in range(n+1)]
stack=deque();ans=[]
stack.append(currnode)
d=0
while stack:
currnode=stack.popleft()
ans.append(currnode)
if visited[currnode]==False:
visited[currnode]=True
for neigbour in graph[currnode]:
if visited[neigbour]==False:
visited[neigbour]=True
stack.append(neigbour)
return ans[-1]
node1=bfs(tree,node)
node2=bfs(tree,node1)
###bfs undirected graph(asumming can reach all nodes)
def bfs_dis(graph,a,b):
visited=[False for x in range(n+1)]
stack=deque()
stack.append((a,0))
while stack:
currnode,d=stack.popleft()
if visited[currnode]==False:
visited[currnode]=True
if currnode==b:
return d,visited
for neigbour in graph[currnode]:
if visited[neigbour]==False:
visited[neigbour]=True
stack.append((neigbour,d+1))
return None
return bfs_dis(tree,node1,node2),node1,node2
visited=[False for x in range(n+1)]
arr=[]
for node in range(1,n+1):
if visited[node]==False:
k,node1,node2=solve(node)
d,visited=k
arr.append([d,node1,node2])
arr.sort()
ans=[0 for x in range(len(arr))]
#### dfs to get center
def dfs(node1,node2,graph):
visited=[False for x in range(n+1)]
stack=[node1]
index=[0 for x in range(n+1)]
while stack:
currnode=stack[-1]
if currnode==node2:
mid=len(stack)//2
return stack[mid]
if visited[currnode]==False:
visited[currnode]=True
for i in range(index[currnode],len(graph[currnode])):
neighbour=graph[currnode][i]
if visited[neighbour]==False:
visited[neighbour]=True
stack.append(neighbour)
index[currnode]+=1
break
else:
stack.pop()
return
for i in range(len(arr)):
### handle exception cases of indi nodes
if arr[i][0]==0:
arr[i][0]+=1
d,node1,node2=arr[i]
mid=dfs(node1,node2,tree)
ans[i]=mid
##update tree
for i in range(len(ans)-1):
tree[ans[-1]].append(ans[i])
tree[ans[i]].append(ans[-1])
ans[i]=(ans[i],ans[-1])
##get new dia
k,n1,n2=solve(1)
d,visited=k
print(d)
##print new nodes
for i in range(len(ans)-1):
print(*ans[i])
``` | output | 1 | 837 | 13 | 1,675 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a forest — an undirected graph with n vertices such that each its connected component is a tree.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
You task is to add some edges (possibly zero) to the graph so that it becomes a tree and the diameter of the tree is minimal possible.
If there are multiple correct answers, print any of them.
Input
The first line contains two integers n and m (1 ≤ n ≤ 1000, 0 ≤ m ≤ n - 1) — the number of vertices of the graph and the number of edges, respectively.
Each of the next m lines contains two integers v and u (1 ≤ v, u ≤ n, v ≠ u) — the descriptions of the edges.
It is guaranteed that the given graph is a forest.
Output
In the first line print the diameter of the resulting tree.
Each of the next (n - 1) - m lines should contain two integers v and u (1 ≤ v, u ≤ n, v ≠ u) — the descriptions of the added edges.
The resulting graph should be a tree and its diameter should be minimal possible.
For m = n - 1 no edges are added, thus the output consists of a single integer — diameter of the given tree.
If there are multiple correct answers, print any of them.
Examples
Input
4 2
1 2
2 3
Output
2
4 2
Input
2 0
Output
1
1 2
Input
3 2
1 3
2 3
Output
2
Note
In the first example adding edges (1, 4) or (3, 4) will lead to a total diameter of 3. Adding edge (2, 4), however, will make it 2.
Edge (1, 2) is the only option you have for the second example. The diameter is 1.
You can't add any edges in the third example. The diameter is already 2. | instruction | 0 | 838 | 13 | 1,676 |
Tags: constructive algorithms, dfs and similar, greedy, trees
Correct Solution:
```
import sys
sys.setrecursionlimit(10000)
class Tree():
def __init__(self, nodes):
self.root = None
class Node():
def __init__(self, val):
self.parent = None
self.val = val
self.children = []
def add(self, child):
self.children.append(child)
def get_max_dist(self, parent,dist):
max_dist = dist
for i in self.children:
if i != parent:
d = i.get_max_dist(self, dist+1)
if max_dist < d:
max_dist = d
return max_dist
def get_dist(self):
return self.get_max_dist(self, 0)
def get_count_ch(self, parent):
count = len(self.children)
for i in self.children:
if i != parent:
count += i.get_count_ch(self)-1
return count
def calc_child(self):
return (self.get_count_ch(None),len(self.children), self.val)
class Forest():
def __init__(self, count):
self.nodes = []
self.count = count
self.set_nodes = set()
def build(self):
roots = []
max_dist = []
#diam = []
list_root = []
for i in self.nodes:
tree =(list(map(lambda x: x.get_dist(), i)))
ma = max(tree)
max_dist.append(ma)
#diam.append(ma)
m = i[tree.index(min(tree))]
roots.append(m)#.val)
if len(roots) > 1:
ind = max_dist.index(max(max_dist))
if len(roots) > 1 and ind != 0:
roots[0], roots[ind] = roots[ind], roots[0]
s = set()
for i in self.nodes:
for j in i:
s.add(j.val)
r = list(set(range(1, n+1))-s)
if len(roots) > 0:# and len(diam) > 0:
for i in range(1, len(roots)):
self.add(roots[0].val, roots[i].val)
list_root.append((roots[0].val, roots[i].val))
#print(roots + r)
for i in r:
self.add(roots[0].val, i)
list_root.append((roots[0].val, i))
else:
if len(r) == 1:
print(0)
return
elif len(r) > 1:
for i in range(1, len(r)):
self.add(r[0], r[i])
list_root.append((r[0], r[i]))
distances = []
for i in self.nodes[0]:
dist =(i.get_dist())
distances.append(dist)
print(max(distances))
for i in list_root:
print(*i)
def add(self, v, u):
self.set_nodes.add(v)
self.set_nodes.add(u)
v_node, v_list = self.find(v)
u_node, u_list = self.find(u)
#print(v_node, u_node)
if v_node == None and u_node == None:
v_node = Node(v)
u_node = Node(u)
v_node.add(u_node)
u_node.add(v_node)
self.nodes.append([v_node, u_node])
elif v_node != None and u_node != None and v_list != u_list:
v_node.add(u_node)
u_node.add(v_node)
v_list += u_list
self.nodes.remove(u_list)
elif v_node == None and u_node != None:
v_node = Node(v)
u_node.add(v_node)
v_node.add(u_node)
u_list.append(v_node)
elif v_node != None and u_node == None:
u_node = Node(u)
v_node.add(u_node)
u_node.add(v_node)
v_list.append(u_node)
def find(self, value):
for i_list in self.nodes:
for i in i_list:
if i.val == value:
return i, i_list
return None, None
n,m = map(int,input().split())
f = Forest(n)
for i in range(m):
v,u = map(int,input().split())
f.add(v, u)
#print(f.nodes)
f.build()
``` | output | 1 | 838 | 13 | 1,677 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a forest — an undirected graph with n vertices such that each its connected component is a tree.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
You task is to add some edges (possibly zero) to the graph so that it becomes a tree and the diameter of the tree is minimal possible.
If there are multiple correct answers, print any of them.
Input
The first line contains two integers n and m (1 ≤ n ≤ 1000, 0 ≤ m ≤ n - 1) — the number of vertices of the graph and the number of edges, respectively.
Each of the next m lines contains two integers v and u (1 ≤ v, u ≤ n, v ≠ u) — the descriptions of the edges.
It is guaranteed that the given graph is a forest.
Output
In the first line print the diameter of the resulting tree.
Each of the next (n - 1) - m lines should contain two integers v and u (1 ≤ v, u ≤ n, v ≠ u) — the descriptions of the added edges.
The resulting graph should be a tree and its diameter should be minimal possible.
For m = n - 1 no edges are added, thus the output consists of a single integer — diameter of the given tree.
If there are multiple correct answers, print any of them.
Examples
Input
4 2
1 2
2 3
Output
2
4 2
Input
2 0
Output
1
1 2
Input
3 2
1 3
2 3
Output
2
Note
In the first example adding edges (1, 4) or (3, 4) will lead to a total diameter of 3. Adding edge (2, 4), however, will make it 2.
Edge (1, 2) is the only option you have for the second example. The diameter is 1.
You can't add any edges in the third example. The diameter is already 2. | instruction | 0 | 839 | 13 | 1,678 |
Tags: constructive algorithms, dfs and similar, greedy, trees
Correct Solution:
```
from collections import defaultdict
from collections import deque
import heapq
import sys
input = sys.stdin.readline
def get_root(s):
v = []
while not s == root[s]:
v.append(s)
s = root[s]
for i in v:
root[i] = s
return s
def unite(s, t):
rs, rt = get_root(s), get_root(t)
if not rs ^ rt:
return
if rank[s] == rank[t]:
rank[rs] += 1
if rank[s] >= rank[t]:
root[rt] = rs
size[rs] += size[rt]
else:
root[rs] = rt
size[rt] += size[rs]
return
def same(s, t):
return True if get_root(s) == get_root(t) else False
def bfs(r):
q = deque()
q.append(r)
dist1[r] = 0
m0, u = 0, r
while q:
i = q.popleft()
di = dist1[i]
if m0 < di:
m0 = di
u = i
for j in G[i]:
if dist1[j] == -1:
dist1[j] = di + 1
q.append(j)
q.append(u)
dist2[u] = 0
m0, v = 0, u
while q:
i = q.popleft()
di = dist2[i]
if m0 < di:
m0 = di
v = i
for j in G[i]:
if dist2[j] == -1:
dist2[j] = di + 1
q.append(j)
q.append(v)
dist3[v] = 0
while q:
i = q.popleft()
di = dist3[i]
for j in G[i]:
if dist3[j] == -1:
dist3[j] = di + 1
q.append(j)
c = r
ma = m0
for i in x[r]:
m1 = max(dist2[i], dist3[i])
if m1 < ma:
ma, c = m1, i
return ma, m0, c
n, m = map(int, input().split())
G = [[] for _ in range(n + 1)]
root = [i for i in range(n + 1)]
rank = [1 for _ in range(n + 1)]
size = [1 for _ in range(n + 1)]
for _ in range(m):
u, v = map(int, input().split())
unite(u, v)
G[u].append(v)
G[v].append(u)
x = defaultdict(lambda : [])
s = set()
for i in range(1, n + 1):
r = get_root(i)
x[r].append(i)
s.add(r)
dist1 = [-1] * (n + 1)
dist2 = [-1] * (n + 1)
dist3 = [-1] * (n + 1)
h = []
l = 0
for i in s:
ma, m0, c = bfs(i)
l = max(l, m0)
heapq.heappush(h, (-ma, c))
s, t = [], []
while h:
m0, c = heapq.heappop(h)
s.append(-m0)
t.append(c)
ans = l
for i in range(len(s)):
si = s[i]
for j in range(i + 1, len(s)):
sj = s[j]
ans = max(ans, si + sj + min(i, 1) + 1)
print(ans)
u = t[0]
for i in range(1, len(t)):
v = t[i]
print(u, v)
``` | output | 1 | 839 | 13 | 1,679 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a forest — an undirected graph with n vertices such that each its connected component is a tree.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
You task is to add some edges (possibly zero) to the graph so that it becomes a tree and the diameter of the tree is minimal possible.
If there are multiple correct answers, print any of them.
Input
The first line contains two integers n and m (1 ≤ n ≤ 1000, 0 ≤ m ≤ n - 1) — the number of vertices of the graph and the number of edges, respectively.
Each of the next m lines contains two integers v and u (1 ≤ v, u ≤ n, v ≠ u) — the descriptions of the edges.
It is guaranteed that the given graph is a forest.
Output
In the first line print the diameter of the resulting tree.
Each of the next (n - 1) - m lines should contain two integers v and u (1 ≤ v, u ≤ n, v ≠ u) — the descriptions of the added edges.
The resulting graph should be a tree and its diameter should be minimal possible.
For m = n - 1 no edges are added, thus the output consists of a single integer — diameter of the given tree.
If there are multiple correct answers, print any of them.
Examples
Input
4 2
1 2
2 3
Output
2
4 2
Input
2 0
Output
1
1 2
Input
3 2
1 3
2 3
Output
2
Note
In the first example adding edges (1, 4) or (3, 4) will lead to a total diameter of 3. Adding edge (2, 4), however, will make it 2.
Edge (1, 2) is the only option you have for the second example. The diameter is 1.
You can't add any edges in the third example. The diameter is already 2. | instruction | 0 | 840 | 13 | 1,680 |
Tags: constructive algorithms, dfs and similar, greedy, trees
Correct Solution:
```
import sys
sys.setrecursionlimit(1100)
def dfs1(u,pre): #find the components
vis[u] = True
now.append(u)
for v in to[u]:
if v!=pre:dfs1(v,u)
def dfs2(u,pre): #calulate the distance
mxdist[u]=dist[u]
for v in to[u]:
if v!=pre:
dist[v] = dist[u]+1
dfs2(v,u)
mxdist[u]=max(mxdist[u],mxdist[v])
try:
lab = 1
n, m = [int(x) for x in input().split()]
to = [[] for i in range(n+10)]
dist = [0 for i in range(n+10)]
mxdist = [0 for i in range(n+10)]
lab = 2
for i in range(m):
u,v = [int(x) for x in input().split()]
to[u].append(v)
to[v].append(u)
com=[]
vis=[False for i in range(n+10)]
for i in range(1,n+1):
if vis[i]==False:
now=[]
dfs1(i,0)
com.append(now)
lab = 3
ct = []
mx = 0
for lis in com:
tmp = []
d = 0
for root in lis:
for u in lis:dist[u]=mxdist[u]=0
dfs2(root,0)
tmp.append((mxdist[root],root))
d = max( d, sum( sorted([ mxdist[u] for u in to[root] ])[-2:] ) )
#print(*[mxdist[u] for u in lis])
mx = max(mx,d)
#print('d =',d)
for x in tmp:
if x[0]==(d+1)//2:
center = [x[1] for x in tmp if x[0]==(d+1)//2][0]
ct.append( ((d+1)//2,center) )
#print(*ct)
lab = 4
ct.sort(reverse=True)
ans = []
for i in range(1,len(ct)):
mx = max(mx,ct[i][0]+1+ct[0][0])
if i>1:mx = max(mx,ct[i][0]+2+ct[1][0])
ans.append((ct[i][1],ct[0][1]))
print(mx)
for p in ans:
print(*p)
except Exception as e:
print('error after lable',lab,', type =',e)
``` | output | 1 | 840 | 13 | 1,681 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a forest — an undirected graph with n vertices such that each its connected component is a tree.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
You task is to add some edges (possibly zero) to the graph so that it becomes a tree and the diameter of the tree is minimal possible.
If there are multiple correct answers, print any of them.
Input
The first line contains two integers n and m (1 ≤ n ≤ 1000, 0 ≤ m ≤ n - 1) — the number of vertices of the graph and the number of edges, respectively.
Each of the next m lines contains two integers v and u (1 ≤ v, u ≤ n, v ≠ u) — the descriptions of the edges.
It is guaranteed that the given graph is a forest.
Output
In the first line print the diameter of the resulting tree.
Each of the next (n - 1) - m lines should contain two integers v and u (1 ≤ v, u ≤ n, v ≠ u) — the descriptions of the added edges.
The resulting graph should be a tree and its diameter should be minimal possible.
For m = n - 1 no edges are added, thus the output consists of a single integer — diameter of the given tree.
If there are multiple correct answers, print any of them.
Examples
Input
4 2
1 2
2 3
Output
2
4 2
Input
2 0
Output
1
1 2
Input
3 2
1 3
2 3
Output
2
Note
In the first example adding edges (1, 4) or (3, 4) will lead to a total diameter of 3. Adding edge (2, 4), however, will make it 2.
Edge (1, 2) is the only option you have for the second example. The diameter is 1.
You can't add any edges in the third example. The diameter is already 2. | instruction | 0 | 841 | 13 | 1,682 |
Tags: constructive algorithms, dfs and similar, greedy, trees
Correct Solution:
```
import sys
def dfs(v, d, prev, i):
global mid
global M
M[v] = False
way[d] = v
if way[d + 1] == 0:
mid[i] = way[d // 2]
mx = (d, v)
for x in E[v]:
if x != prev:
mx = max(mx, dfs(x, d + 1, v, i))
return mx
sys.setrecursionlimit(2000)
n, m = map(int, input().split())
E = [[] for i in range(n + 1)]
for i in range(m):
a, b = map(int, input().split())
E[a].append(b)
E[b].append(a)
mid = [0] * (n + 2)
c = 0
k = 0
way = [0] * (n + 2)
M = [True] * (n + 1)
M[0] = False
i = -1
while True in M:
i += 1
idx = M.index(True)
p1 = dfs(idx, 0, 0, i)[1]
way = [0] * (n + 2)
s, p2 = dfs(p1, 0, 0, i)
if s > c:
c = s
k = i
r = []
for j in range(0, i + 1):
if j == k:
continue
r.append((mid[k], mid[j]))
E[mid[k]].append(mid[j])
E[mid[j]].append(mid[k])
p1 = dfs(1, 0, 0, n + 1)[1]
s, p2 = dfs(p1, 0, 0, n + 1)
print(s)
for item in r:
print(item[0], item[1])
``` | output | 1 | 841 | 13 | 1,683 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a forest — an undirected graph with n vertices such that each its connected component is a tree.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
You task is to add some edges (possibly zero) to the graph so that it becomes a tree and the diameter of the tree is minimal possible.
If there are multiple correct answers, print any of them.
Input
The first line contains two integers n and m (1 ≤ n ≤ 1000, 0 ≤ m ≤ n - 1) — the number of vertices of the graph and the number of edges, respectively.
Each of the next m lines contains two integers v and u (1 ≤ v, u ≤ n, v ≠ u) — the descriptions of the edges.
It is guaranteed that the given graph is a forest.
Output
In the first line print the diameter of the resulting tree.
Each of the next (n - 1) - m lines should contain two integers v and u (1 ≤ v, u ≤ n, v ≠ u) — the descriptions of the added edges.
The resulting graph should be a tree and its diameter should be minimal possible.
For m = n - 1 no edges are added, thus the output consists of a single integer — diameter of the given tree.
If there are multiple correct answers, print any of them.
Examples
Input
4 2
1 2
2 3
Output
2
4 2
Input
2 0
Output
1
1 2
Input
3 2
1 3
2 3
Output
2
Note
In the first example adding edges (1, 4) or (3, 4) will lead to a total diameter of 3. Adding edge (2, 4), however, will make it 2.
Edge (1, 2) is the only option you have for the second example. The diameter is 1.
You can't add any edges in the third example. The diameter is already 2. | instruction | 0 | 842 | 13 | 1,684 |
Tags: constructive algorithms, dfs and similar, greedy, trees
Correct Solution:
```
from collections import defaultdict, deque
from math import ceil
n, m = map(int, input().split())
graph = defaultdict(list)
for i in range(m):
u, v = map(int, input().split())
graph[u].append(v)
graph[v].append(u)
vis = set()
diams = []
for node in range(1, n + 1):
if node not in vis:
#print('node: ', node)
vis.add(node)
q = deque()
cur_big = 0
cur_big_node = node
q.append((node, node, 0))
while q:
pro_n, par, val = q.popleft()
for child in graph[pro_n]:
if child != par:
vis.add(child)
q.append((child, pro_n, val + 1))
if val > cur_big:
cur_big = val
cur_big_node = pro_n
diameter = 0
end_node = cur_big_node
q.append((cur_big_node, cur_big_node, 0))
pa = defaultdict(int)
while q:
pro_n, par, val = q.popleft()
pa[pro_n] = par
for child in graph[pro_n]:
if child != par:
q.append((child, pro_n, val + 1))
if val > diameter:
diameter = val
end_node = pro_n
cen_node = end_node
for i in range(diameter//2):
cen_node = pa[cen_node]
diams.append((diameter, cen_node))
diams.sort(reverse=True)
if len(diams) > 2:
if diams[0][0] == diams[1][0] == diams[2][0]:
res = ceil(diams[0][0]/2) + ceil(diams[1][0]/2) + 2
else:
res = max(diams[0][0], ceil(diams[0][0]/2) + ceil(diams[1][0]/2) + 1)
elif len(diams) >= 2:
res = max(diams[0][0], ceil(diams[0][0]/2) + ceil(diams[1][0]/2) + 1)
else:
res = diams[0][0]
print(res)
for i in range(1,len(diams)):
print(diams[0][1], diams[i][1])
``` | output | 1 | 842 | 13 | 1,685 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a forest — an undirected graph with n vertices such that each its connected component is a tree.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
You task is to add some edges (possibly zero) to the graph so that it becomes a tree and the diameter of the tree is minimal possible.
If there are multiple correct answers, print any of them.
Input
The first line contains two integers n and m (1 ≤ n ≤ 1000, 0 ≤ m ≤ n - 1) — the number of vertices of the graph and the number of edges, respectively.
Each of the next m lines contains two integers v and u (1 ≤ v, u ≤ n, v ≠ u) — the descriptions of the edges.
It is guaranteed that the given graph is a forest.
Output
In the first line print the diameter of the resulting tree.
Each of the next (n - 1) - m lines should contain two integers v and u (1 ≤ v, u ≤ n, v ≠ u) — the descriptions of the added edges.
The resulting graph should be a tree and its diameter should be minimal possible.
For m = n - 1 no edges are added, thus the output consists of a single integer — diameter of the given tree.
If there are multiple correct answers, print any of them.
Examples
Input
4 2
1 2
2 3
Output
2
4 2
Input
2 0
Output
1
1 2
Input
3 2
1 3
2 3
Output
2
Note
In the first example adding edges (1, 4) or (3, 4) will lead to a total diameter of 3. Adding edge (2, 4), however, will make it 2.
Edge (1, 2) is the only option you have for the second example. The diameter is 1.
You can't add any edges in the third example. The diameter is already 2.
Submitted Solution:
```
from collections import defaultdict
from collections import deque
import heapq
import sys
input = sys.stdin.readline
def get_root(s):
v = []
while not s == root[s]:
v.append(s)
s = root[s]
for i in v:
root[i] = s
return s
def unite(s, t):
rs, rt = get_root(s), get_root(t)
if not rs ^ rt:
return
if rank[s] == rank[t]:
rank[rs] += 1
if rank[s] >= rank[t]:
root[rt] = rs
size[rs] += size[rt]
else:
root[rs] = rt
size[rt] += size[rs]
return
def same(s, t):
return True if get_root(s) == get_root(t) else False
def bfs(r):
q = deque()
q.append(r)
dist1[r] = 0
m0, u = 0, r
while q:
i = q.popleft()
di = dist1[i]
if m0 < di:
m0 = di
u = i
for j in G[i]:
if dist1[j] == -1:
dist1[j] = di + 1
q.append(j)
q.append(u)
dist2[u] = 0
m0, v = 0, u
while q:
i = q.popleft()
di = dist2[i]
if m0 < di:
m0 = di
v = i
for j in G[i]:
if dist2[j] == -1:
dist2[j] = di + 1
q.append(j)
q.append(v)
dist3[v] = 0
while q:
i = q.popleft()
di = dist3[i]
for j in G[i]:
if dist3[j] == -1:
dist3[j] = di + 1
q.append(j)
c = r
ma = m0
for i in x[r]:
m1 = max(dist2[i], dist3[i])
if m1 < ma:
m0, c = m1, i
return ma, m0, c
n, m = map(int, input().split())
G = [[] for _ in range(n + 1)]
root = [i for i in range(n + 1)]
rank = [1 for _ in range(n + 1)]
size = [1 for _ in range(n + 1)]
for _ in range(m):
u, v = map(int, input().split())
unite(u, v)
G[u].append(v)
G[v].append(u)
x = defaultdict(lambda : [])
s = set()
for i in range(1, n + 1):
r = get_root(i)
x[r].append(i)
s.add(r)
dist1 = [-1] * (n + 1)
dist2 = [-1] * (n + 1)
dist3 = [-1] * (n + 1)
h = []
l = 0
for i in s:
ma, m0, c = bfs(i)
l = max(l, ma)
heapq.heappush(h, (-m0, c))
q = deque()
for i in range(n - m):
if i % 2:
q.append(heapq.heappop(h))
else:
q.appendleft(heapq.heappop(h))
s, t = [], []
while q:
m0, c = q.popleft()
s.append(-m0)
t.append(c)
ans = l
for i in range(len(s)):
si = s[i]
for j in range(i + 1, len(s)):
sj = s[j]
ans = max(si + sj + j - i, ans)
print(ans)
for i in range(len(t) - 1):
u, v = t[i], t[i + 1]
print(u, v)
``` | instruction | 0 | 843 | 13 | 1,686 |
No | output | 1 | 843 | 13 | 1,687 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a forest — an undirected graph with n vertices such that each its connected component is a tree.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
You task is to add some edges (possibly zero) to the graph so that it becomes a tree and the diameter of the tree is minimal possible.
If there are multiple correct answers, print any of them.
Input
The first line contains two integers n and m (1 ≤ n ≤ 1000, 0 ≤ m ≤ n - 1) — the number of vertices of the graph and the number of edges, respectively.
Each of the next m lines contains two integers v and u (1 ≤ v, u ≤ n, v ≠ u) — the descriptions of the edges.
It is guaranteed that the given graph is a forest.
Output
In the first line print the diameter of the resulting tree.
Each of the next (n - 1) - m lines should contain two integers v and u (1 ≤ v, u ≤ n, v ≠ u) — the descriptions of the added edges.
The resulting graph should be a tree and its diameter should be minimal possible.
For m = n - 1 no edges are added, thus the output consists of a single integer — diameter of the given tree.
If there are multiple correct answers, print any of them.
Examples
Input
4 2
1 2
2 3
Output
2
4 2
Input
2 0
Output
1
1 2
Input
3 2
1 3
2 3
Output
2
Note
In the first example adding edges (1, 4) or (3, 4) will lead to a total diameter of 3. Adding edge (2, 4), however, will make it 2.
Edge (1, 2) is the only option you have for the second example. The diameter is 1.
You can't add any edges in the third example. The diameter is already 2.
Submitted Solution:
```
from collections import defaultdict, deque
from math import ceil
n, m = map(int, input().split())
graph = defaultdict(list)
for i in range(m):
u, v = map(int, input().split())
graph[u].append(v)
graph[v].append(u)
vis = set()
node = 1
vis.add(node)
q = deque()
cur_big = 0
cur_big_node = node
q.append((node, -1, 0))
while q:
pro_n, par, val = q.popleft()
for child in graph[pro_n]:
if child != par:
vis.add(child)
q.append((child, pro_n, val + 1))
if val > cur_big:
cur_big = val
cur_big_node = node
diameter = 0
old_center = cur_big_node
q.append((cur_big_node, -1, 0))
result = []
pa = defaultdict(int)
while q:
pro_n, par, val = q.popleft()
pa[pro_n] = par
for child in graph[pro_n]:
if child != par:
q.append((child, pro_n, val + 1))
if val > diameter:
diameter = val
old_center = pro_n
prev_dia = diameter
center = ceil(diameter / 2)
ans = diameter
for i in range(center):
old_center = pa[old_center]
center = max(1,ceil(diameter / 2))
for node in range(1, n + 1):
if node not in vis:
vis.add(node)
q = deque()
cur_big = 0
cur_big_node = node
q.append((node, -1, 0))
while q:
pro_n, par, val = q.popleft()
for child in graph[pro_n]:
if child != par:
vis.add(child)
q.append((child, pro_n, val + 1))
if val > cur_big:
cur_big = val
cur_big_node = node
diameter = 0
end_node = cur_big_node
q.append((cur_big_node, -1, 0))
pa = defaultdict(int)
while q:
pro_n, par, val = q.popleft()
pa[pro_n] = par
for child in graph[pro_n]:
if child != par:
q.append((child, pro_n, val + 1))
if val > diameter:
diameter = val
end_node = pro_n
new_dia = ceil(diameter / 2)
cen_node = end_node
for i in range(new_dia):
cen_node = pa[cen_node]
result.append((old_center, cen_node))
ans = max(prev_dia, diameter)
ans = max(ans, center + new_dia + 1)
prev_dia = diameter
print(ans)
for i in result:
print(i[0], i[1])
``` | instruction | 0 | 844 | 13 | 1,688 |
No | output | 1 | 844 | 13 | 1,689 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a forest — an undirected graph with n vertices such that each its connected component is a tree.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
You task is to add some edges (possibly zero) to the graph so that it becomes a tree and the diameter of the tree is minimal possible.
If there are multiple correct answers, print any of them.
Input
The first line contains two integers n and m (1 ≤ n ≤ 1000, 0 ≤ m ≤ n - 1) — the number of vertices of the graph and the number of edges, respectively.
Each of the next m lines contains two integers v and u (1 ≤ v, u ≤ n, v ≠ u) — the descriptions of the edges.
It is guaranteed that the given graph is a forest.
Output
In the first line print the diameter of the resulting tree.
Each of the next (n - 1) - m lines should contain two integers v and u (1 ≤ v, u ≤ n, v ≠ u) — the descriptions of the added edges.
The resulting graph should be a tree and its diameter should be minimal possible.
For m = n - 1 no edges are added, thus the output consists of a single integer — diameter of the given tree.
If there are multiple correct answers, print any of them.
Examples
Input
4 2
1 2
2 3
Output
2
4 2
Input
2 0
Output
1
1 2
Input
3 2
1 3
2 3
Output
2
Note
In the first example adding edges (1, 4) or (3, 4) will lead to a total diameter of 3. Adding edge (2, 4), however, will make it 2.
Edge (1, 2) is the only option you have for the second example. The diameter is 1.
You can't add any edges in the third example. The diameter is already 2.
Submitted Solution:
```
from collections import defaultdict, deque
from math import ceil
n, m = map(int, input().split())
graph = defaultdict(list)
for i in range(m):
u, v = map(int, input().split())
graph[u].append(v)
graph[v].append(u)
vis = set()
node = 1
vis.add(node)
q = deque()
cur_big = 0
cur_big_node = node
q.append((node, -1, 0))
while q:
pro_n, par, val = q.popleft()
for child in graph[pro_n]:
if child != par:
vis.add(child)
q.append((child, pro_n, val + 1))
if val > cur_big:
cur_big = val
cur_big_node = pro_n
diameter = 0
old_center = cur_big_node
q.append((cur_big_node, -1, 0))
result = []
pa = defaultdict(int)
while q:
pro_n, par, val = q.popleft()
pa[pro_n] = par
for child in graph[pro_n]:
if child != par:
q.append((child, pro_n, val + 1))
if val > diameter:
diameter = val
old_center = pro_n
prev_dia = diameter
center = ceil(diameter / 2)
ans = diameter
for i in range(center):
old_center = pa[old_center]
if n > 2:
center = max(1,center)
for node in range(1, n + 1):
if node not in vis:
#print('node: ', node)
vis.add(node)
q = deque()
cur_big = 0
cur_big_node = node
q.append((node, -1, 0))
while q:
pro_n, par, val = q.popleft()
for child in graph[pro_n]:
if child != par:
vis.add(child)
q.append((child, pro_n, val + 1))
if val > cur_big:
cur_big = val
cur_big_node = pro_n
diameter = 0
end_node = cur_big_node
q.append((cur_big_node, -1, 0))
pa = defaultdict(int)
while q:
pro_n, par, val = q.popleft()
pa[pro_n] = par
for child in graph[pro_n]:
if child != par:
q.append((child, pro_n, val + 1))
if val > diameter:
diameter = val
end_node = pro_n
new_dia = ceil(diameter / 2)
cen_node = end_node
for i in range(new_dia):
cen_node = pa[cen_node]
result.append((old_center, cen_node))
ans = max(ans, diameter)
ans = max(ans, center + new_dia + 1)
if new_dia + 1 > center:
center = new_dia + 1
print(ans)
for i in result:
print(i[0], i[1])
``` | instruction | 0 | 845 | 13 | 1,690 |
No | output | 1 | 845 | 13 | 1,691 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a forest — an undirected graph with n vertices such that each its connected component is a tree.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
You task is to add some edges (possibly zero) to the graph so that it becomes a tree and the diameter of the tree is minimal possible.
If there are multiple correct answers, print any of them.
Input
The first line contains two integers n and m (1 ≤ n ≤ 1000, 0 ≤ m ≤ n - 1) — the number of vertices of the graph and the number of edges, respectively.
Each of the next m lines contains two integers v and u (1 ≤ v, u ≤ n, v ≠ u) — the descriptions of the edges.
It is guaranteed that the given graph is a forest.
Output
In the first line print the diameter of the resulting tree.
Each of the next (n - 1) - m lines should contain two integers v and u (1 ≤ v, u ≤ n, v ≠ u) — the descriptions of the added edges.
The resulting graph should be a tree and its diameter should be minimal possible.
For m = n - 1 no edges are added, thus the output consists of a single integer — diameter of the given tree.
If there are multiple correct answers, print any of them.
Examples
Input
4 2
1 2
2 3
Output
2
4 2
Input
2 0
Output
1
1 2
Input
3 2
1 3
2 3
Output
2
Note
In the first example adding edges (1, 4) or (3, 4) will lead to a total diameter of 3. Adding edge (2, 4), however, will make it 2.
Edge (1, 2) is the only option you have for the second example. The diameter is 1.
You can't add any edges in the third example. The diameter is already 2.
Submitted Solution:
```
def dfs(v, d, prev, i):
global mid
global M
M[v] = False
way[d] = v
if way[d + 1] == 0:
mid[i] = way[d // 2]
mx = (d, v)
for x in E[v]:
if x != prev:
mx = max(mx, dfs(x, d + 1, v, i))
return mx
n, m = map(int, input().split())
# костыль
if m == n - 1:
print(m)
exit()
E = [[] for i in range(n + 1)]
for i in range(m):
a, b = map(int, input().split())
E[a].append(b)
E[b].append(a)
mid = [0] * (n + 2)
c = 0
k = 0
way = [0] * (n + 2)
M = [True] * (n + 1)
M[0] = False
i = -1
while True in M:
i += 1
idx = M.index(True)
p1 = dfs(idx, 0, 0, i)[1]
way = [0] * (n + 2)
s, p2 = dfs(p1, 0, 0, i)
if s > c:
c = s
k = i
r = []
for j in range(0, i + 1):
if j == k:
continue
r.append((mid[k], mid[j]))
E[mid[k]].append(mid[j])
E[mid[j]].append(mid[k])
p1 = dfs(1, 0, 0, n + 1)[1]
s, p2 = dfs(p1, 0, 0, n + 1)
print(s)
for item in r:
print(item[0], item[1])
``` | instruction | 0 | 846 | 13 | 1,692 |
No | output | 1 | 846 | 13 | 1,693 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a directed graph with n vertices and m directed edges without self-loops or multiple edges.
Let's denote the k-coloring of a digraph as following: you color each edge in one of k colors. The k-coloring is good if and only if there no cycle formed by edges of same color.
Find a good k-coloring of given digraph with minimum possible k.
Input
The first line contains two integers n and m (2 ≤ n ≤ 5000, 1 ≤ m ≤ 5000) — the number of vertices and edges in the digraph, respectively.
Next m lines contain description of edges — one per line. Each edge is a pair of integers u and v (1 ≤ u, v ≤ n, u ≠ v) — there is directed edge from u to v in the graph.
It is guaranteed that each ordered pair (u, v) appears in the list of edges at most once.
Output
In the first line print single integer k — the number of used colors in a good k-coloring of given graph.
In the second line print m integers c_1, c_2, ..., c_m (1 ≤ c_i ≤ k), where c_i is a color of the i-th edge (in order as they are given in the input).
If there are multiple answers print any of them (you still have to minimize k).
Examples
Input
4 5
1 2
1 3
3 4
2 4
1 4
Output
1
1 1 1 1 1
Input
3 3
1 2
2 3
3 1
Output
2
1 1 2 | instruction | 0 | 917 | 13 | 1,834 |
Tags: constructive algorithms, dfs and similar, graphs
Correct Solution:
```
import sys
sys.setrecursionlimit(10**9)
def dfs(a):
global adj,vis,st
j=0
vis[a]=1
for i in adj[a][:]:
if vis[i[0]]==0:
dfs(i[0])
adj[a][j][1]=1
elif vis[i[0]]==2:
adj[a][j][1]=1
else:
st=2
adj[a][j][1]=2
j+=1
vis[a]=2
n,m=map(int,input().split())
it=[]
adj=[[] for i in range(n)]
#print(adj)
for _ in range(m):
a,b=map(int,input().split())
adj[a-1].append([b-1,1,_])
#print(adj)
vis=[0]*n
st=1
for ii in range(n):
if vis[ii]==0:
dfs(ii)
print(st)
ans=[0]*m
for i in range(n):
for j in adj[i]:
# print(j[2],j[1])
ans[j[2]]=j[1]
print(*ans)
``` | output | 1 | 917 | 13 | 1,835 |
End of preview. Expand
in Data Studio
- Downloads last month
- 8