message stringlengths 2 49.9k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 446 108k | cluster float64 13 13 | __index_level_0__ int64 892 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with N vertices numbered 1, 2, ..., N. The i-th edge connects Vertex a_i and Vertex b_i. You are also given a string S of length N consisting of `0` and `1`. The i-th character of S represents the number of pieces placed on Vertex i.
Snuke will perform the following operation some number of times:
* Choose two pieces the distance between which is at least 2, and bring these pieces closer to each other by 1. More formally, choose two vertices u and v, each with one or more pieces, and consider the shortest path between them. Here the path must contain at least two edges. Then, move one piece from u to its adjacent vertex on the path, and move one piece from v to its adjacent vertex on the path.
By repeating this operation, Snuke wants to have all the pieces on the same vertex. Is this possible? If the answer is yes, also find the minimum number of operations required to achieve it.
Constraints
* 2 \leq N \leq 2000
* |S| = N
* S consists of `0` and `1`, and contains at least one `1`.
* 1 \leq a_i, b_i \leq N(a_i \neq b_i)
* The edges (a_1, b_1), (a_2, b_2), ..., (a_{N - 1}, b_{N - 1}) forms a tree.
Input
Input is given from Standard Input in the following format:
N
S
a_1 b_1
a_2 b_2
:
a_{N - 1} b_{N - 1}
Output
If it is impossible to have all the pieces on the same vertex, print `-1`. If it is possible, print the minimum number of operations required.
Examples
Input
7
0010101
1 2
2 3
1 4
4 5
1 6
6 7
Output
3
Input
7
0010110
1 2
2 3
1 4
4 5
1 6
6 7
Output
-1
Input
2
01
1 2
Output
0
Submitted Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
"""
・部分木の中で操作を行った場合の、残りdepth和の最小値と最大値を持ってdp
・補助的にコマの個数も持つ
・最大値:ただのdepthの和
・最小値:一番負担の大きな木から他の部分木を引いていった場合だが…
・最小値+最大値から全部の最大値の和を引く形で更新
"""
N = int(readline())
S = readline().rstrip()
m = map(int,read().split())
AB = zip(m,m)
INF = 10**18
graph = [[] for _ in range(N+1)]
for a,b in AB:
graph[a].append(b)
graph[b].append(a)
def solve_rooted(root):
parent = [0] * (N+1)
ts = []
stack = [root]
while stack:
x = stack.pop()
ts.append(x)
for y in graph[x]:
if y == parent[x]:
continue
parent[y] = x
stack.append(y)
max_dep = [0]*(N+1)
min_dep = [0]*(N+1)
cnt = [0] * (N+1)
for i,x in enumerate(S,1):
cnt[i]=x-ord('0')
for v in ts[::-1]:
p = parent[v]
max_dep_sum = 0
x = 0
for c in graph[v]:
if c==p:
continue
cnt[v] += cnt[c]
d1 = max_dep[c]; d2 = min_dep[c]
d1 += cnt[c]; d2 += cnt[c]
max_dep_sum += d1
if x<d1+d2:
x=d1+d2
max_dep[v] = max_dep_sum
x -= max_dep_sum
if x<0:
x=max_dep_sum&1
min_dep[v] = x
if min_dep[root]:
return INF
return max_dep[root]//2
answer = min(solve_rooted(v) for v in range(1,N+1))
if answer == INF:
answer = -1
print(answer)
``` | instruction | 0 | 26,288 | 13 | 52,576 |
Yes | output | 1 | 26,288 | 13 | 52,577 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with N vertices numbered 1, 2, ..., N. The i-th edge connects Vertex a_i and Vertex b_i. You are also given a string S of length N consisting of `0` and `1`. The i-th character of S represents the number of pieces placed on Vertex i.
Snuke will perform the following operation some number of times:
* Choose two pieces the distance between which is at least 2, and bring these pieces closer to each other by 1. More formally, choose two vertices u and v, each with one or more pieces, and consider the shortest path between them. Here the path must contain at least two edges. Then, move one piece from u to its adjacent vertex on the path, and move one piece from v to its adjacent vertex on the path.
By repeating this operation, Snuke wants to have all the pieces on the same vertex. Is this possible? If the answer is yes, also find the minimum number of operations required to achieve it.
Constraints
* 2 \leq N \leq 2000
* |S| = N
* S consists of `0` and `1`, and contains at least one `1`.
* 1 \leq a_i, b_i \leq N(a_i \neq b_i)
* The edges (a_1, b_1), (a_2, b_2), ..., (a_{N - 1}, b_{N - 1}) forms a tree.
Input
Input is given from Standard Input in the following format:
N
S
a_1 b_1
a_2 b_2
:
a_{N - 1} b_{N - 1}
Output
If it is impossible to have all the pieces on the same vertex, print `-1`. If it is possible, print the minimum number of operations required.
Examples
Input
7
0010101
1 2
2 3
1 4
4 5
1 6
6 7
Output
3
Input
7
0010110
1 2
2 3
1 4
4 5
1 6
6 7
Output
-1
Input
2
01
1 2
Output
0
Submitted Solution:
```
import sys
sys.setrecursionlimit(10**4)
N=int(input())
S=input()
edge=[[] for i in range(N)]
for i in range(N-1):
a,b=map(int,input().split())
edge[a-1].append(b-1)
edge[b-1].append(a-1)
depth=[0]*N
num=[0]*N
sd=[0]*N
def dfs(v,pv):
res=depth[v]*(S[v]=="1")
n=int(S[v])
for nv in edge[v]:
if nv!=pv:
depth[nv]=depth[v]+1
dfs(nv,v)
res+=sd[nv]
n+=num[nv]
sd[v]=res
num[v]=n
def dfs2(v,pv):
hosei=depth[v]
S=sd[v]-num[v]*hosei
if S%2==0:
check=0
node=-1
for nv in edge[v]:
if nv!=pv:
if sd[nv]-num[nv]*hosei>S//2:
check=sd[nv]-num[nv]*hosei
node=nv
if not check:
return S//2
else:
minus=dfs2(node,v)
if check-2*minus<=S-check:
return S//2
else:
return S-check+minus
else:
check=0
node=-1
k=S//2
for nv in edge[v]:
if nv!=pv:
if sd[nv]-num[nv]*hosei>k+1:
check=sd[nv]-num[nv]*hosei
node=nv
if not check:
return k
else:
minus=dfs2(node,v)
if check-2*minus<=S-check:
return k
else:
return S-check+minus
ans=10**18
for i in range(N):
depth[i]=0
dfs(i,-1)
#print(i,depth)
test=dfs2(i,-1)
if test*2==sd[i]:
ans=min(ans,test)
if ans==10**18:
print(-1)
else:
print(ans)
``` | instruction | 0 | 26,289 | 13 | 52,578 |
No | output | 1 | 26,289 | 13 | 52,579 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with N vertices numbered 1, 2, ..., N. The i-th edge connects Vertex a_i and Vertex b_i. You are also given a string S of length N consisting of `0` and `1`. The i-th character of S represents the number of pieces placed on Vertex i.
Snuke will perform the following operation some number of times:
* Choose two pieces the distance between which is at least 2, and bring these pieces closer to each other by 1. More formally, choose two vertices u and v, each with one or more pieces, and consider the shortest path between them. Here the path must contain at least two edges. Then, move one piece from u to its adjacent vertex on the path, and move one piece from v to its adjacent vertex on the path.
By repeating this operation, Snuke wants to have all the pieces on the same vertex. Is this possible? If the answer is yes, also find the minimum number of operations required to achieve it.
Constraints
* 2 \leq N \leq 2000
* |S| = N
* S consists of `0` and `1`, and contains at least one `1`.
* 1 \leq a_i, b_i \leq N(a_i \neq b_i)
* The edges (a_1, b_1), (a_2, b_2), ..., (a_{N - 1}, b_{N - 1}) forms a tree.
Input
Input is given from Standard Input in the following format:
N
S
a_1 b_1
a_2 b_2
:
a_{N - 1} b_{N - 1}
Output
If it is impossible to have all the pieces on the same vertex, print `-1`. If it is possible, print the minimum number of operations required.
Examples
Input
7
0010101
1 2
2 3
1 4
4 5
1 6
6 7
Output
3
Input
7
0010110
1 2
2 3
1 4
4 5
1 6
6 7
Output
-1
Input
2
01
1 2
Output
0
Submitted Solution:
```
import sys
sys.setrecursionlimit(10000)
def first_dfs(v, p, stones, dists):
stone = s[v]
dist = 0
for u in links[v]:
if u == p:
continue
us, ud = first_dfs(u, v, stones, dists)
stone += us
dist += ud + us
stones[v] = stone
dists[v] = dist
return stone, dist
def second_dfs(v, p, pd, ans):
children_dists = []
for u in links[v]:
if u == p:
children_dists.append(pd)
continue
children_dists.append(stones[u] + dists[u])
sd = sum(children_dists)
h, m = divmod(sd, 2)
# print(v, p, sd, h, m, children_dists, pd)
if m == 0 and all(h >= d for d in children_dists):
ans.append(h)
for u in links[v]:
if u == p:
continue
us = stones[u]
ud = dists[u]
if us > 0 and ud > 0:
second_dfs(u, v, sd - us - dists[u] + (all_stones - us), ans)
n = int(input())
s = list(map(int, input()))
all_stones = sum(s)
if all_stones == 1:
print(0)
exit()
links = [set() for _ in [0] * n]
for line in sys.stdin:
a, b = map(int, line.split())
a -= 1
b -= 1
links[a].add(b)
links[b].add(a)
# print(links)
stones = [0] * n
dists = [0] * n
first_dfs(0, -1, stones, dists)
# print(stones)
# print(dists)
ans = []
second_dfs(0, -1, 0, ans)
if ans:
print(min(ans))
else:
print(-1)
``` | instruction | 0 | 26,290 | 13 | 52,580 |
No | output | 1 | 26,290 | 13 | 52,581 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with N vertices numbered 1, 2, ..., N. The i-th edge connects Vertex a_i and Vertex b_i. You are also given a string S of length N consisting of `0` and `1`. The i-th character of S represents the number of pieces placed on Vertex i.
Snuke will perform the following operation some number of times:
* Choose two pieces the distance between which is at least 2, and bring these pieces closer to each other by 1. More formally, choose two vertices u and v, each with one or more pieces, and consider the shortest path between them. Here the path must contain at least two edges. Then, move one piece from u to its adjacent vertex on the path, and move one piece from v to its adjacent vertex on the path.
By repeating this operation, Snuke wants to have all the pieces on the same vertex. Is this possible? If the answer is yes, also find the minimum number of operations required to achieve it.
Constraints
* 2 \leq N \leq 2000
* |S| = N
* S consists of `0` and `1`, and contains at least one `1`.
* 1 \leq a_i, b_i \leq N(a_i \neq b_i)
* The edges (a_1, b_1), (a_2, b_2), ..., (a_{N - 1}, b_{N - 1}) forms a tree.
Input
Input is given from Standard Input in the following format:
N
S
a_1 b_1
a_2 b_2
:
a_{N - 1} b_{N - 1}
Output
If it is impossible to have all the pieces on the same vertex, print `-1`. If it is possible, print the minimum number of operations required.
Examples
Input
7
0010101
1 2
2 3
1 4
4 5
1 6
6 7
Output
3
Input
7
0010110
1 2
2 3
1 4
4 5
1 6
6 7
Output
-1
Input
2
01
1 2
Output
0
Submitted Solution:
```
import sys
sys.setrecursionlimit(10000)
input = sys.stdin.readline
def f(v, vs):
kminmax = rkoma = fff = ffmx = 0
for u in d[v]:
if u in vs:
continue
vs.add(u)
k1, koma, ff = f(u, vs)
if k1 > kminmax:
kminmax, ffmx = k1, ff
rkoma += koma
fff += ff
r1 = kminmax+ffmx-fff if kminmax > fff - ffmx else fff % 2
rkoma += km[v]
return r1+rkoma, rkoma, fff+rkoma
N = int(input())
km = [0] + [int(i) for i in str(input().strip())]
d = [set() for _ in range(N+1)]
for _ in range(N-1):
x, y = map(int, input().split())
d[x].add(y)
d[y].add(x)
r=-1
for i in range(N):
a, c, fff = f(i+1, {i+1})
if a == c:
r = (fff-c)//2
print(r)
``` | instruction | 0 | 26,291 | 13 | 52,582 |
No | output | 1 | 26,291 | 13 | 52,583 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with N vertices numbered 1, 2, ..., N. The i-th edge connects Vertex a_i and Vertex b_i. You are also given a string S of length N consisting of `0` and `1`. The i-th character of S represents the number of pieces placed on Vertex i.
Snuke will perform the following operation some number of times:
* Choose two pieces the distance between which is at least 2, and bring these pieces closer to each other by 1. More formally, choose two vertices u and v, each with one or more pieces, and consider the shortest path between them. Here the path must contain at least two edges. Then, move one piece from u to its adjacent vertex on the path, and move one piece from v to its adjacent vertex on the path.
By repeating this operation, Snuke wants to have all the pieces on the same vertex. Is this possible? If the answer is yes, also find the minimum number of operations required to achieve it.
Constraints
* 2 \leq N \leq 2000
* |S| = N
* S consists of `0` and `1`, and contains at least one `1`.
* 1 \leq a_i, b_i \leq N(a_i \neq b_i)
* The edges (a_1, b_1), (a_2, b_2), ..., (a_{N - 1}, b_{N - 1}) forms a tree.
Input
Input is given from Standard Input in the following format:
N
S
a_1 b_1
a_2 b_2
:
a_{N - 1} b_{N - 1}
Output
If it is impossible to have all the pieces on the same vertex, print `-1`. If it is possible, print the minimum number of operations required.
Examples
Input
7
0010101
1 2
2 3
1 4
4 5
1 6
6 7
Output
3
Input
7
0010110
1 2
2 3
1 4
4 5
1 6
6 7
Output
-1
Input
2
01
1 2
Output
0
Submitted Solution:
```
print("wakaranai")
``` | instruction | 0 | 26,292 | 13 | 52,584 |
No | output | 1 | 26,292 | 13 | 52,585 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected tree, consisting of n vertices.
The vertex is called a leaf if it has exactly one vertex adjacent to it.
The distance between some pair of vertices is the number of edges in the shortest path between them.
Let's call some set of leaves beautiful if the maximum distance between any pair of leaves in it is less or equal to k.
You want to split all leaves into non-intersecting beautiful sets. What is the minimal number of sets in such a split?
Input
The first line contains two integers n and k (3 ≤ n ≤ 10^6, 1 ≤ k ≤ 10^6) — the number of vertices in the tree and the maximum distance between any pair of leaves in each beautiful set.
Each of the next n - 1 lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ n) — the description of the i-th edge.
It is guaranteed that the given edges form a tree.
Output
Print a single integer — the minimal number of beautiful sets the split can have.
Examples
Input
9 3
1 2
1 3
2 4
2 5
3 6
6 7
6 8
3 9
Output
2
Input
5 3
1 2
2 3
3 4
4 5
Output
2
Input
6 1
1 2
1 3
1 4
1 5
1 6
Output
5
Note
Here is the graph for the first example:
<image>
Submitted Solution:
```
print('Bring back MightyToMo')
``` | instruction | 0 | 26,561 | 13 | 53,122 |
No | output | 1 | 26,561 | 13 | 53,123 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected tree, consisting of n vertices.
The vertex is called a leaf if it has exactly one vertex adjacent to it.
The distance between some pair of vertices is the number of edges in the shortest path between them.
Let's call some set of leaves beautiful if the maximum distance between any pair of leaves in it is less or equal to k.
You want to split all leaves into non-intersecting beautiful sets. What is the minimal number of sets in such a split?
Input
The first line contains two integers n and k (3 ≤ n ≤ 10^6, 1 ≤ k ≤ 10^6) — the number of vertices in the tree and the maximum distance between any pair of leaves in each beautiful set.
Each of the next n - 1 lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ n) — the description of the i-th edge.
It is guaranteed that the given edges form a tree.
Output
Print a single integer — the minimal number of beautiful sets the split can have.
Examples
Input
9 3
1 2
1 3
2 4
2 5
3 6
6 7
6 8
3 9
Output
2
Input
5 3
1 2
2 3
3 4
4 5
Output
2
Input
6 1
1 2
1 3
1 4
1 5
1 6
Output
5
Note
Here is the graph for the first example:
<image>
Submitted Solution:
```
print(2)
``` | instruction | 0 | 26,562 | 13 | 53,124 |
No | output | 1 | 26,562 | 13 | 53,125 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to choose at most ⌊n/2⌋ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
You will be given multiple independent queries to answer.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of queries.
Then t queries follow.
The first line of each query contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges, respectively.
The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge.
There are no self-loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected.
It is guaranteed that ∑ m ≤ 2 ⋅ 10^5 over all queries.
Output
For each query print two lines.
In the first line print k (1 ≤ ⌊n/2⌋) — the number of chosen vertices.
In the second line print k distinct integers c_1, c_2, ..., c_k in any order, where c_i is the index of the i-th chosen vertex.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
Example
Input
2
4 6
1 2
1 3
1 4
2 3
2 4
3 4
6 8
2 5
5 4
4 3
4 1
1 3
2 3
2 6
5 6
Output
2
1 3
3
4 3 6
Note
In the first query any vertex or any pair of vertices will suffice.
<image>
Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices 2 and 4) but three is also ok.
<image> | instruction | 0 | 26,621 | 13 | 53,242 |
Tags: dfs and similar, dsu, graphs, shortest paths, trees
Correct Solution:
```
n, m = map(int, input().split())
countn = [0] * (n+1)
g = dict()
for i in range(m):
u, v = map(int, input().split())
countn[u] += 1
countn[v] += 1
if u in g:
g[u].append(v)
else:
g[u] = [v]
if v in g:
g[v].append(u)
else:
g[v] = [u]
cIndex = countn.index(max(countn))
visited = [False] * (n+1)
qVisit = [cIndex]
visited[cIndex] = True
while len(qVisit) > 0:
i = qVisit.pop()
for j in g[i]:
if not(visited[j]):
print(i, j)
visited[j] = True
qVisit.append(j)
``` | output | 1 | 26,621 | 13 | 53,243 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to choose at most ⌊n/2⌋ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
You will be given multiple independent queries to answer.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of queries.
Then t queries follow.
The first line of each query contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges, respectively.
The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge.
There are no self-loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected.
It is guaranteed that ∑ m ≤ 2 ⋅ 10^5 over all queries.
Output
For each query print two lines.
In the first line print k (1 ≤ ⌊n/2⌋) — the number of chosen vertices.
In the second line print k distinct integers c_1, c_2, ..., c_k in any order, where c_i is the index of the i-th chosen vertex.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
Example
Input
2
4 6
1 2
1 3
1 4
2 3
2 4
3 4
6 8
2 5
5 4
4 3
4 1
1 3
2 3
2 6
5 6
Output
2
1 3
3
4 3 6
Note
In the first query any vertex or any pair of vertices will suffice.
<image>
Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices 2 and 4) but three is also ok.
<image> | instruction | 0 | 26,622 | 13 | 53,244 |
Tags: dfs and similar, dsu, graphs, shortest paths, trees
Correct Solution:
```
def digraph_from_input():
digraph = dict()
n, m = map(int, input().split())
for t in range(m):
z1, z2 = map(int, input().split())
if z1 not in digraph:
digraph[z1] = set([z2])
else:
digraph[z1].add(z2)
if z2 not in digraph:
digraph[z2] = set([z1])
else:
digraph[z2].add(z1)
return digraph
def BFC(digraph, v):
s2 = set()
s1 = set()
oboid = set()
ans = dict()
havepa = set()
havepa.add(v)
s1.add(v)
while s1 != set():
for element in s1:
last_element = element
if element not in oboid:
oboid.add(element)
for key in digraph[element]:
if key not in havepa:
s2.add(key)
havepa.add(key)
ans[key] = last_element
s1 = s2
s2 = set()
return ans
digraph = digraph_from_input()
v = 1
for i in digraph:
if len(digraph[i]) > len(digraph[v]):
v = i
q = BFC(digraph, v)
for i in q:
print(i, q[i])
``` | output | 1 | 26,622 | 13 | 53,245 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to choose at most ⌊n/2⌋ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
You will be given multiple independent queries to answer.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of queries.
Then t queries follow.
The first line of each query contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges, respectively.
The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge.
There are no self-loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected.
It is guaranteed that ∑ m ≤ 2 ⋅ 10^5 over all queries.
Output
For each query print two lines.
In the first line print k (1 ≤ ⌊n/2⌋) — the number of chosen vertices.
In the second line print k distinct integers c_1, c_2, ..., c_k in any order, where c_i is the index of the i-th chosen vertex.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
Example
Input
2
4 6
1 2
1 3
1 4
2 3
2 4
3 4
6 8
2 5
5 4
4 3
4 1
1 3
2 3
2 6
5 6
Output
2
1 3
3
4 3 6
Note
In the first query any vertex or any pair of vertices will suffice.
<image>
Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices 2 and 4) but three is also ok.
<image> | instruction | 0 | 26,623 | 13 | 53,246 |
Tags: dfs and similar, dsu, graphs, shortest paths, trees
Correct Solution:
```
n,m=map(int,input().split())
adj=[0]*(n+1)
for i in range(n+1):
adj[i]=[]
s=0
for i in range(m):
x,y=map(int,input().split())
adj[x].append(y)
adj[y].append(x)
if len(adj[x])>len(adj[s]):
s=x
if len(adj[y])>len(adj[s]):
s=y
stk=[]
mp={}
mp[s]=1
vis=[0]*(n+1)
for i in range(len(adj[s])):
stk.append([s,adj[s][i]])
if adj[s][i] not in mp:
mp[adj[s][i]]=1
i=0
vis[s]=1
# for l in mp:
# print (l)
while(i<len(stk)):
k=stk[i][1]
if vis[k]==0:
for j in range(len(adj[k])):
if k not in mp or adj[k][j] not in mp:
stk.append([k,adj[k][j]])
mp[k]=1
mp[adj[k][j]]=1
vis[k]=1
i+=1
for i in range(len(stk)):
print(*stk[i])
``` | output | 1 | 26,623 | 13 | 53,247 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to choose at most ⌊n/2⌋ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
You will be given multiple independent queries to answer.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of queries.
Then t queries follow.
The first line of each query contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges, respectively.
The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge.
There are no self-loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected.
It is guaranteed that ∑ m ≤ 2 ⋅ 10^5 over all queries.
Output
For each query print two lines.
In the first line print k (1 ≤ ⌊n/2⌋) — the number of chosen vertices.
In the second line print k distinct integers c_1, c_2, ..., c_k in any order, where c_i is the index of the i-th chosen vertex.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
Example
Input
2
4 6
1 2
1 3
1 4
2 3
2 4
3 4
6 8
2 5
5 4
4 3
4 1
1 3
2 3
2 6
5 6
Output
2
1 3
3
4 3 6
Note
In the first query any vertex or any pair of vertices will suffice.
<image>
Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices 2 and 4) but three is also ok.
<image> | instruction | 0 | 26,624 | 13 | 53,248 |
Tags: dfs and similar, dsu, graphs, shortest paths, trees
Correct Solution:
```
# -*- coding: utf-8 -*-
import sys
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7
def dfs(nodes, src):
N = len(nodes)
stack = [(src, 0)]
dist = [INF] * N
dist[src] = 0
while stack:
u, c = stack.pop()
for v in nodes[u]:
if dist[v] != INF:
continue
dist[v] = c + 1
stack.append((v, c+1))
return dist
ans = []
for _ in range(INT()):
N, M = MAP()
nodes = [[] for i in range(N)]
for _ in range(M):
a, b = MAP()
a -= 1; b -= 1
nodes[a].append(b)
nodes[b].append(a)
res = dfs(nodes, 0)
ans1 = []
ans2 = []
for u, c in enumerate(res):
if c % 2 == 0:
ans1.append(str(u+1))
else:
ans2.append(str(u+1))
if len(ans1) <= len(ans2):
ans.append(str(len(ans1)))
ans.append(' '.join(ans1))
else:
ans.append(str(len(ans2)))
ans.append(' '.join(ans2))
print('\n'.join(ans))
``` | output | 1 | 26,624 | 13 | 53,249 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to choose at most ⌊n/2⌋ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
You will be given multiple independent queries to answer.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of queries.
Then t queries follow.
The first line of each query contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges, respectively.
The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge.
There are no self-loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected.
It is guaranteed that ∑ m ≤ 2 ⋅ 10^5 over all queries.
Output
For each query print two lines.
In the first line print k (1 ≤ ⌊n/2⌋) — the number of chosen vertices.
In the second line print k distinct integers c_1, c_2, ..., c_k in any order, where c_i is the index of the i-th chosen vertex.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
Example
Input
2
4 6
1 2
1 3
1 4
2 3
2 4
3 4
6 8
2 5
5 4
4 3
4 1
1 3
2 3
2 6
5 6
Output
2
1 3
3
4 3 6
Note
In the first query any vertex or any pair of vertices will suffice.
<image>
Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices 2 and 4) but three is also ok.
<image> | instruction | 0 | 26,625 | 13 | 53,250 |
Tags: dfs and similar, dsu, graphs, shortest paths, trees
Correct Solution:
```
#import sys
#sys.stdin = open('input.txt')
n, m = map(int, input().split())
ar = [[] for i in range(n + 1)]
mx = [0] * (n + 1)
for i in range(m):
x, y = map(int, input().split())
mx[x] += 1
mx[y] += 1
ar[x].append(y)
ar[y].append(x)
st = mx.index(max(mx))
used = [False] * (n + 1)
ans = []
q = []
used[st] = True
def bfs(st, tt=0):
q.append(st)
while tt < len(q):
v = q[tt]
for i in ar[v]:
if not used[i]:
used[i] = True
q.append(i)
ans.append((v, i))
tt += 1
bfs(st)
for i in ans:
print(' '.join(map(str, i)))
``` | output | 1 | 26,625 | 13 | 53,251 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to choose at most ⌊n/2⌋ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
You will be given multiple independent queries to answer.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of queries.
Then t queries follow.
The first line of each query contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges, respectively.
The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge.
There are no self-loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected.
It is guaranteed that ∑ m ≤ 2 ⋅ 10^5 over all queries.
Output
For each query print two lines.
In the first line print k (1 ≤ ⌊n/2⌋) — the number of chosen vertices.
In the second line print k distinct integers c_1, c_2, ..., c_k in any order, where c_i is the index of the i-th chosen vertex.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
Example
Input
2
4 6
1 2
1 3
1 4
2 3
2 4
3 4
6 8
2 5
5 4
4 3
4 1
1 3
2 3
2 6
5 6
Output
2
1 3
3
4 3 6
Note
In the first query any vertex or any pair of vertices will suffice.
<image>
Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices 2 and 4) but three is also ok.
<image> | instruction | 0 | 26,626 | 13 | 53,252 |
Tags: dfs and similar, dsu, graphs, shortest paths, trees
Correct Solution:
```
######################################################################
# Write your code here
import sys
input = sys.stdin.readline
#import resource
#resource.setrlimit(resource.RLIMIT_STACK, [0x10000000, resource.RLIM_INFINITY])
#sys.setrecursionlimit(0x100000)
# Write your code here
RI = lambda : [int(x) for x in input().strip().split()]
rw = lambda : input().strip().split()
from collections import defaultdict as df
#import heapq
#heapq.heapify(li) heappush(li,4) heappop(li)
#import random
#random.shuffle(list)
#infinite = float('inf')
#######################################################################)
def dfs(a,n):
depth=[0]*n
depth[a]=0
x=1
stack=[a]
vis[a]=1
l=[0,0]
l[0]+=1
#stackindex=0
#print(stack)
while(len(stack)!=0):
p=stack.pop()
#print(p)
#stackindex-=1
for i in adj[p]:
if(vis[i]==1):
continue
vis[i]=1
stack.append(i)
#stackindex+=1
depth[i]=depth[p]^1
l[depth[i]]+=1
x=(x+1)%2
#print(depth)
#print(vis)
#print("hi")
#print(depth)
#print(l)
s=n//2
if(l[0]<=s):
print(l[0])
for i in range(n):
if(depth[i]==0):
print(i+1,end=" ")
else:
print(l[1])
for i in range(n):
if(depth[i]==1):
print(i+1,end=" ")
print("")
t=int(input())
#adj=[[] for i in range(200010)]
#vis=[0]*(200010)
for _ in range(t):
n,m=RI()
adj=[[] for i in range(n)]
vis=[0]*(n)
for i in range(m):
a,b=RI()
adj[a-1].append(b-1)
adj[b-1].append(a-1)
#print(adj)
# print("hi",0)
dfs(0,n)
``` | output | 1 | 26,626 | 13 | 53,253 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to choose at most ⌊n/2⌋ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
You will be given multiple independent queries to answer.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of queries.
Then t queries follow.
The first line of each query contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges, respectively.
The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge.
There are no self-loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected.
It is guaranteed that ∑ m ≤ 2 ⋅ 10^5 over all queries.
Output
For each query print two lines.
In the first line print k (1 ≤ ⌊n/2⌋) — the number of chosen vertices.
In the second line print k distinct integers c_1, c_2, ..., c_k in any order, where c_i is the index of the i-th chosen vertex.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
Example
Input
2
4 6
1 2
1 3
1 4
2 3
2 4
3 4
6 8
2 5
5 4
4 3
4 1
1 3
2 3
2 6
5 6
Output
2
1 3
3
4 3 6
Note
In the first query any vertex or any pair of vertices will suffice.
<image>
Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices 2 and 4) but three is also ok.
<image> | instruction | 0 | 26,627 | 13 | 53,254 |
Tags: dfs and similar, dsu, graphs, shortest paths, trees
Correct Solution:
```
# 1133F1
import collections
def do():
graph = collections.defaultdict(list)
nodes, edges = map(int, input().split(" "))
ind = [0] * (nodes + 1)
for _ in range(edges):
x, y = map(int, input().split(" "))
graph[x].append(y)
graph[y].append(x)
ind[x] += 1
ind[y] += 1
root = 1
mi = ind[1]
for i in range(1, nodes + 1):
if ind[i] > mi:
mi = ind[i]
root = i
seen = [0] * (nodes + 1)
seen[root] = 1
res = set()
q = collections.deque()
for nei in graph[root]:
seen[nei] = 1
res.add((root, nei))
q.append(nei)
while q:
cur = q.popleft()
for nei in graph[cur]:
if not seen[nei]:
seen[nei] = 1
res.add((cur, nei))
q.append(nei)
for x, y in list(res):
print(str(x) + " " + str(y))
return 0
do()
``` | output | 1 | 26,627 | 13 | 53,255 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to choose at most ⌊n/2⌋ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
You will be given multiple independent queries to answer.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of queries.
Then t queries follow.
The first line of each query contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges, respectively.
The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge.
There are no self-loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected.
It is guaranteed that ∑ m ≤ 2 ⋅ 10^5 over all queries.
Output
For each query print two lines.
In the first line print k (1 ≤ ⌊n/2⌋) — the number of chosen vertices.
In the second line print k distinct integers c_1, c_2, ..., c_k in any order, where c_i is the index of the i-th chosen vertex.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
Example
Input
2
4 6
1 2
1 3
1 4
2 3
2 4
3 4
6 8
2 5
5 4
4 3
4 1
1 3
2 3
2 6
5 6
Output
2
1 3
3
4 3 6
Note
In the first query any vertex or any pair of vertices will suffice.
<image>
Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices 2 and 4) but three is also ok.
<image> | instruction | 0 | 26,628 | 13 | 53,256 |
Tags: dfs and similar, dsu, graphs, shortest paths, trees
Correct Solution:
```
# TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!!
# TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!!
# TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!!
# TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!!
# TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!!
# TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!!
# TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!!
# TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!!
from sys import stdin, stdout
import collections
import math
Q = int(input())
for q in range(Q):
N,M = [int(x) for x in stdin.readline().split()]
degree = {}
for i in range(1,N+1):
degree[i] = []
for i in range(M):
u,v = [int(x) for x in stdin.readline().split()]
degree[u].append(v)
degree[v].append(u)
visited = [0]*(N+1)
label = [0]*(N+1)
stack = [1]
label[1] = 1
ones = 0
twos = 0
while stack:
p = stack.pop()
visited[p] = 1
for node in degree[p]:
if visited[node]==0:
stack.append(node)
if label[p]==1:
label[node] = 2
else:
label[node] = 1
for i in range(1,N+1):
if label[i]==1:
ones += 1
else:
twos += 1
if ones>twos:
print(twos)
for i in range(1,N+1):
if label[i]==2:
print(i,end=' ')
print('',end='\n')
else:
print(ones)
for i in range(1,N+1):
if label[i]==1:
print(i,end=' ')
print('',end='\n')
``` | output | 1 | 26,628 | 13 | 53,257 |
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 unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to choose at most ⌊n/2⌋ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
You will be given multiple independent queries to answer.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of queries.
Then t queries follow.
The first line of each query contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges, respectively.
The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge.
There are no self-loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected.
It is guaranteed that ∑ m ≤ 2 ⋅ 10^5 over all queries.
Output
For each query print two lines.
In the first line print k (1 ≤ ⌊n/2⌋) — the number of chosen vertices.
In the second line print k distinct integers c_1, c_2, ..., c_k in any order, where c_i is the index of the i-th chosen vertex.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
Example
Input
2
4 6
1 2
1 3
1 4
2 3
2 4
3 4
6 8
2 5
5 4
4 3
4 1
1 3
2 3
2 6
5 6
Output
2
1 3
3
4 3 6
Note
In the first query any vertex or any pair of vertices will suffice.
<image>
Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices 2 and 4) but three is also ok.
<image>
Submitted Solution:
```
from sys import stdin,stdout
from collections import *
from math import ceil, floor , log
st=lambda:list(stdin.readline().strip())
li=lambda:list(map(int,stdin.readline().split()))
mp=lambda:map(int,stdin.readline().split())
inp=lambda:int(stdin.readline())
pr=lambda n: stdout.write(str(n)+"\n")
mod=1000000007
INF=float('inf')
def solve():
n,m= mp()
d={i:[] for i in range(1,n+1)}
deg={i:0 for i in range(1,n+1)}
for i in range(m):
a,b = mp()
deg[a]+=1
deg[b]+=1
d[a].append(b)
d[b].append(a)
ma=-1
val=0
for i in deg:
if deg[i]>ma:
ma= deg[i]
val= i
v=[False for i in range(n+1)]
q=deque()
q.append(val)
v[val]=True
while q:
a=q.popleft()
for i in d[a]:
if not v[i]:
print(i,a)
v[i]=True
q.append(i)
for _ in range(1):
#print('Case',str(_+1)+':')
solve()
``` | instruction | 0 | 26,629 | 13 | 53,258 |
Yes | output | 1 | 26,629 | 13 | 53,259 |
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 unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to choose at most ⌊n/2⌋ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
You will be given multiple independent queries to answer.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of queries.
Then t queries follow.
The first line of each query contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges, respectively.
The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge.
There are no self-loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected.
It is guaranteed that ∑ m ≤ 2 ⋅ 10^5 over all queries.
Output
For each query print two lines.
In the first line print k (1 ≤ ⌊n/2⌋) — the number of chosen vertices.
In the second line print k distinct integers c_1, c_2, ..., c_k in any order, where c_i is the index of the i-th chosen vertex.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
Example
Input
2
4 6
1 2
1 3
1 4
2 3
2 4
3 4
6 8
2 5
5 4
4 3
4 1
1 3
2 3
2 6
5 6
Output
2
1 3
3
4 3 6
Note
In the first query any vertex or any pair of vertices will suffice.
<image>
Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices 2 and 4) but three is also ok.
<image>
Submitted Solution:
```
I=lambda:list(map(int,input().split()))
import sys
input=sys.stdin.readline
import collections as cc
for tc in range(int(input())):
n,m=I()
g=cc.defaultdict(list)
deg=[0]*(n+1)
for i in range(m):
x,y=I()
g[x].append(y)
g[y].append(x)
deg[x]+=1
deg[y]+=1
ar=[]
for i in range(1,n+1):
ar.append([i,deg[i]])
ar.sort(key=lambda i:i[1],reverse=True)
ans=[]
visi=[0]*(n+1)
comp=[]
for i in ar:
x,y=i
if not visi[x]:
ans.append(x)
visi[x]=1
for j in g[x]:
if visi[j]==0:
comp.append(j)
visi[j]=1
if len(ans)>n//2:
print(len(comp))
print(*comp)
else:
print(len(ans))
print(*ans)
``` | instruction | 0 | 26,630 | 13 | 53,260 |
Yes | output | 1 | 26,630 | 13 | 53,261 |
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 unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to choose at most ⌊n/2⌋ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
You will be given multiple independent queries to answer.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of queries.
Then t queries follow.
The first line of each query contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges, respectively.
The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge.
There are no self-loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected.
It is guaranteed that ∑ m ≤ 2 ⋅ 10^5 over all queries.
Output
For each query print two lines.
In the first line print k (1 ≤ ⌊n/2⌋) — the number of chosen vertices.
In the second line print k distinct integers c_1, c_2, ..., c_k in any order, where c_i is the index of the i-th chosen vertex.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
Example
Input
2
4 6
1 2
1 3
1 4
2 3
2 4
3 4
6 8
2 5
5 4
4 3
4 1
1 3
2 3
2 6
5 6
Output
2
1 3
3
4 3 6
Note
In the first query any vertex or any pair of vertices will suffice.
<image>
Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices 2 and 4) but three is also ok.
<image>
Submitted Solution:
```
'''Author- Akshit Monga'''
from sys import stdin,stdout
input = stdin.readline
def dfs(start):
global n,g
vis=[0 for i in range(n + 1)]
dis=[0 for i in range(n + 1)]
stack=[]
stack.append((start,0))
while len(stack):
s=stack.pop()
node=s[0]
par=s[1]
if not vis[node]:
vis[node]=1
dis[node]=dis[par]^1
for i in g[node]:
if not vis[i]:
stack.append((i,node))
for i in range(1,n+1):
if dis[i]:
odds.append(i)
else:
evens.append(i)
t = int(input())
for _ in range(t):
n,m=map(int,input().split())
g=[[] for i in range(n+1)]
for i in range(m):
a,b=map(int,input().split())
g[a].append(b)
g[b].append(a)
evens=[]
odds=[]
dfs(1)
if len(evens)<=n//2:
print(len(evens))
print(*evens)
else:
print(len(odds))
print(*odds)
``` | instruction | 0 | 26,631 | 13 | 53,262 |
Yes | output | 1 | 26,631 | 13 | 53,263 |
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 unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to choose at most ⌊n/2⌋ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
You will be given multiple independent queries to answer.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of queries.
Then t queries follow.
The first line of each query contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges, respectively.
The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge.
There are no self-loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected.
It is guaranteed that ∑ m ≤ 2 ⋅ 10^5 over all queries.
Output
For each query print two lines.
In the first line print k (1 ≤ ⌊n/2⌋) — the number of chosen vertices.
In the second line print k distinct integers c_1, c_2, ..., c_k in any order, where c_i is the index of the i-th chosen vertex.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
Example
Input
2
4 6
1 2
1 3
1 4
2 3
2 4
3 4
6 8
2 5
5 4
4 3
4 1
1 3
2 3
2 6
5 6
Output
2
1 3
3
4 3 6
Note
In the first query any vertex or any pair of vertices will suffice.
<image>
Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices 2 and 4) but three is also ok.
<image>
Submitted Solution:
```
from collections import defaultdict, deque
from sys import stdin
input = stdin.readline
if __name__ == '__main__':
n, m = map(int, input().split())
arr = [tuple(map(int, input().split())) for _ in range(m)]
# What if I choose the vertex with already the maximum degree and create a MST from it?
dct = defaultdict(lambda: [])
for u, v in arr:
dct[u].append(v)
dct[v].append(u)
# S1: Find vertex with max degree
mx = max(dct.items(), key=lambda t: len(t[1]))[0]
# S2: RAW BFS
viz = {mx}
st = deque([mx])
es = []
while st:
r = st.popleft()
for c in dct[r]:
if c not in viz:
st.append(c)
viz.add(c)
es.append((r, c))
for e in es:
print(*e)
``` | instruction | 0 | 26,632 | 13 | 53,264 |
Yes | output | 1 | 26,632 | 13 | 53,265 |
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 unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to choose at most ⌊n/2⌋ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
You will be given multiple independent queries to answer.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of queries.
Then t queries follow.
The first line of each query contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges, respectively.
The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge.
There are no self-loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected.
It is guaranteed that ∑ m ≤ 2 ⋅ 10^5 over all queries.
Output
For each query print two lines.
In the first line print k (1 ≤ ⌊n/2⌋) — the number of chosen vertices.
In the second line print k distinct integers c_1, c_2, ..., c_k in any order, where c_i is the index of the i-th chosen vertex.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
Example
Input
2
4 6
1 2
1 3
1 4
2 3
2 4
3 4
6 8
2 5
5 4
4 3
4 1
1 3
2 3
2 6
5 6
Output
2
1 3
3
4 3 6
Note
In the first query any vertex or any pair of vertices will suffice.
<image>
Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices 2 and 4) but three is also ok.
<image>
Submitted Solution:
```
n, m = map(int, input().split())
dl = [0]*(n+1)
cl = []
for i in range(m):
u, v = map(int, input().split())
dl[u]+=1
dl[v]+=1
cl.append((u, v))
pos = dl.index(max(dl))
for i in range(m):
u, v = cl[i][0], cl[i][1]
if dl[u]<=1 or dl[v]<=1 or u==pos or v==pos:
print(u, v)
dl[u]-=1
dl[v]-=1
``` | instruction | 0 | 26,633 | 13 | 53,266 |
No | output | 1 | 26,633 | 13 | 53,267 |
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 unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to choose at most ⌊n/2⌋ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
You will be given multiple independent queries to answer.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of queries.
Then t queries follow.
The first line of each query contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges, respectively.
The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge.
There are no self-loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected.
It is guaranteed that ∑ m ≤ 2 ⋅ 10^5 over all queries.
Output
For each query print two lines.
In the first line print k (1 ≤ ⌊n/2⌋) — the number of chosen vertices.
In the second line print k distinct integers c_1, c_2, ..., c_k in any order, where c_i is the index of the i-th chosen vertex.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
Example
Input
2
4 6
1 2
1 3
1 4
2 3
2 4
3 4
6 8
2 5
5 4
4 3
4 1
1 3
2 3
2 6
5 6
Output
2
1 3
3
4 3 6
Note
In the first query any vertex or any pair of vertices will suffice.
<image>
Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices 2 and 4) but three is also ok.
<image>
Submitted Solution:
```
from collections import Counter, defaultdict
def go():
n, m = map(int, input().split(' '))
graph = defaultdict(list)
for _ in range(m):
a, b = map(int, input().split(' '))
graph[a].append(b)
graph[b].append(a)
visited = [False] * (n + 1)
levels = [0] * (n + 1)
queue = [1]
visited[1] = True
while queue:
current = queue.pop()
for child in graph[current]:
if not visited[child]:
levels[child] = levels[current] + 1
queue.append(child)
visited[child] = True
c = Counter(levels)
c[0] -= 1
odd = even = 0
for i in c:
if i % 2 == 0:
even += c[i]
else:
odd += c[i]
rest = 1
o = []
if odd > even:
rest = 0
for i in range(1, n):
if levels[i] % 2 == rest:
o.append(i)
return '{}\n{}'.format(len(o), ' '.join(str(i) for i in o))
for t in range(int(input())):
print(go())
``` | instruction | 0 | 26,634 | 13 | 53,268 |
No | output | 1 | 26,634 | 13 | 53,269 |
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 unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to choose at most ⌊n/2⌋ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
You will be given multiple independent queries to answer.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of queries.
Then t queries follow.
The first line of each query contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges, respectively.
The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge.
There are no self-loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected.
It is guaranteed that ∑ m ≤ 2 ⋅ 10^5 over all queries.
Output
For each query print two lines.
In the first line print k (1 ≤ ⌊n/2⌋) — the number of chosen vertices.
In the second line print k distinct integers c_1, c_2, ..., c_k in any order, where c_i is the index of the i-th chosen vertex.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
Example
Input
2
4 6
1 2
1 3
1 4
2 3
2 4
3 4
6 8
2 5
5 4
4 3
4 1
1 3
2 3
2 6
5 6
Output
2
1 3
3
4 3 6
Note
In the first query any vertex or any pair of vertices will suffice.
<image>
Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices 2 and 4) but three is also ok.
<image>
Submitted Solution:
```
class UnionFind:
def __init__(self, n):
self.par = [i for i in range(n)]
self.rank = [1] * (n + 1)
self.rank[0] = 0
def union(self, x, y):
if not self.same_set(x, y):
par_x = self.find(x)
par_y = self.find(y)
if self.rank[par_x] >= self.rank[par_y]:
self.rank[par_x] += self.rank[par_y]
self.rank[par_y] = 0
self.par[par_y] = par_x
else:
self.rank[par_y] += self.rank[par_x]
self.rank[par_x] = 0
self.par[par_x] = par_y
self.find(x)
self.find(y)
def find(self, x):
if self.par[x] == x: return x
self.par[x] = self.find(self.par[x])
return self.par[x]
def same_set(self, x, y):
return self.find(x) == self.find(y)
n, m = map(int, input().split())
adj = [[] for i in range(n + 1)]
arestas = []
for i in range(m):
a, b = map(int, input().split())
adj[a].append(b)
adj[b].append(a)
arestas.append((a, b))
maior = 1
for i in range(n):
if len(adj[i]) > len(adj[maior]): maior = i
ans = []
uf = UnionFind(n+1)
for v in adj[maior]:
ans.append((maior, v))
uf.union(maior, v)
for a, b in arestas:
if a == maior or b == maior: continue
if not uf.same_set(a, b):
ans.append((a, b))
uf.union(a, b)
for a, b in ans:
print(a, b)
``` | instruction | 0 | 26,635 | 13 | 53,270 |
No | output | 1 | 26,635 | 13 | 53,271 |
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 unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to choose at most ⌊n/2⌋ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
You will be given multiple independent queries to answer.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of queries.
Then t queries follow.
The first line of each query contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and the number of edges, respectively.
The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge.
There are no self-loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected.
It is guaranteed that ∑ m ≤ 2 ⋅ 10^5 over all queries.
Output
For each query print two lines.
In the first line print k (1 ≤ ⌊n/2⌋) — the number of chosen vertices.
In the second line print k distinct integers c_1, c_2, ..., c_k in any order, where c_i is the index of the i-th chosen vertex.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
Example
Input
2
4 6
1 2
1 3
1 4
2 3
2 4
3 4
6 8
2 5
5 4
4 3
4 1
1 3
2 3
2 6
5 6
Output
2
1 3
3
4 3 6
Note
In the first query any vertex or any pair of vertices will suffice.
<image>
Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices 2 and 4) but three is also ok.
<image>
Submitted Solution:
```
from collections import deque
q = int(input())
for i in range(q):
n, m = map(int, input().split())
edges = [[] for i in range(n)]
st = [0] * n
done = [0] * n
start = 0
visited = [0] * n
rem = n // 2
arr = []
for i in range(m):
a, b = map(int, input().split())
edges[a - 1].append(b - 1)
edges[b - 1].append(a - 1)
st[a - 1] += 1
st[b - 1] += 1
for i in range(len(st)):
if st[i] == 1 and done[i] == 0:
done[edges[i][0]] = 1
arr.append(i + 1)
for j in range(len(edges[edges[i][0]])):
done[edges[edges[i][0]][j]] = 1
rem -= 1
for i in range(len(st)):
st[i] = [st[i], i]
st = sorted(st)
st1 = []
for i in range(len(st) - 1, -1, -1):
st1.append(st[i])
for i in range(len(st1)):
if rem == 0:
continue
v = st1[i][1]
done[v] = 1
rem -= 1
arr.append(v + 1)
for edge in edges[st1[i][1]]:
done[edge] = 1
print(len(arr))
print(*arr)
#q = deque()
#q.append(start)
# while len(q) > 0:
# v = q.pop()
# visited[v] = 1
# for i in range(len(edges[v])):
# if visited[edges[v][i]] == 1:
# continue
# else:
# visited[edges[v][i]] = 1
#
``` | instruction | 0 | 26,636 | 13 | 53,272 |
No | output | 1 | 26,636 | 13 | 53,273 |
Provide a correct Python 3 solution for this coding contest problem.
Given an undirected weighted graph G, you should find one of spanning trees specified as follows.
The graph G is an ordered pair (V, E), where V is a set of vertices {v1, v2, ... , vn} and E is a set of undirected edges {e1, e2, ... , em}. Each edge e ∈ E has its weight w(e).
A spanning tree T is a tree (a connected subgraph without cycles) which connects all the n vertices with n - 1 edges. The slimness of a spanning tree T is defined as the difference between the largest weight and the smallest weight among the n - 1 edges of T.
<image>
Figure 5: A graph G and the weights of the edges
For example, a graph G in Figure 5(a) has four vertices {v1, v2, v3, v4} and five undirected edges {e1, e2, e3, e4, e5}. The weights of the edges are w(e1) = 3, w(e2) = 5, w(e3) = 6, w(e4) = 6, w(e5) = 7 as shown in Figure 5(b).
<image>
Figure 6: Examples of the spanning trees of G
There are several spanning trees for G. Four of them are depicted in Figure 6(a)-(d). The spanning tree Ta in Figure 6(a) has three edges whose weights are 3, 6 and 7. The largest weight is 7 and the smallest weight is 3 so that the slimness of the tree Ta is 4. The slimnesses of spanning trees Tb , Tc and Td shown in Figure 6(b), (c) and (d) are 3, 2 and 1, respectively. You can easily see the slimness of any other spanning tree is greater than or equal to 1, thus the spanning tree Td in Figure 6(d) is one of the slimmest spanning trees whose slimness is 1.
Your job is to write a program that computes the smallest slimness.
Input
The input consists of multiple datasets, followed by a line containing two zeros separated by a space. Each dataset has the following format.
n m
a1 b1 w1
.
.
.
am bm wm
Every input item in a dataset is a non-negative integer. Items in a line are separated by a space.
n is the number of the vertices and m the number of the edges. You can assume 2 ≤ n ≤ 100 and 0 ≤ m ≤ n(n - 1)/2. ak and bk (k = 1, ... , m) are positive integers less than or equal to n, which represent the two vertices vak and vbk connected by the kth edge ek. wk is a positive integer less than or equal to 10000, which indicates the weight of ek . You can assume that the graph G = (V, E) is simple, that is, there are no self-loops (that connect the same vertex) nor parallel edges (that are two or more edges whose both ends are the same two vertices).
Output
For each dataset, if the graph has spanning trees, the smallest slimness among them should be printed. Otherwise, -1 should be printed. An output should not contain extra characters.
Example
Input
4 5
1 2 3
1 3 5
1 4 6
2 4 6
3 4 7
4 6
1 2 10
1 3 100
1 4 90
2 3 20
2 4 80
3 4 40
2 1
1 2 1
3 0
3 1
1 2 1
3 3
1 2 2
2 3 5
1 3 6
5 10
1 2 110
1 3 120
1 4 130
1 5 120
2 3 110
2 4 120
2 5 130
3 4 120
3 5 110
4 5 120
5 10
1 2 9384
1 3 887
1 4 2778
1 5 6916
2 3 7794
2 4 8336
2 5 5387
3 4 493
3 5 6650
4 5 1422
5 8
1 2 1
2 3 100
3 4 100
4 5 100
1 5 50
2 5 50
3 5 50
4 1 150
0 0
Output
1
20
0
-1
-1
1
0
1686
50 | instruction | 0 | 27,342 | 13 | 54,684 |
"Correct Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
class UnionFind:
def __init__(self, size):
self.table = [-1 for _ in range(size)]
def find(self, x):
if self.table[x] < 0:
return x
else:
self.table[x] = self.find(self.table[x])
return self.table[x]
def union(self, x, y):
s1 = self.find(x)
s2 = self.find(y)
if s1 != s2:
if self.table[s1] <= self.table[s2]:
self.table[s1] += self.table[s2]
self.table[s2] = s1
else:
self.table[s2] += self.table[s1]
self.table[s1] = s2
return True
return False
def subsetall(self):
a = []
for i in range(len(self.table)):
if self.table[i] < 0:
a.append((i, -self.table[i]))
return a
def main():
rr = []
while True:
n,m = LI()
if n == 0:
break
a = sorted([LI()[::-1] for _ in range(m)])
for i in range(2,n+1):
a.append([inf, 1, i])
r = inf
for i in range(m):
uf = UnionFind(n+1)
mt = 0
uc = 0
for t,x,y in a[i:]:
if uf.union(x,y):
mt = t
uc += 1
if uc == n-1:
break
if mt == inf:
break
tr = mt - a[i][0]
if r > tr:
r = tr
if r == inf:
r = -1
rr.append(r)
return '\n'.join(map(str, rr))
print(main())
``` | output | 1 | 27,342 | 13 | 54,685 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree with n nodes. You have to write non-negative integers on its edges so that the following condition would be satisfied:
For every two nodes i, j, look at the path between them and count the sum of numbers on the edges of this path. Write all obtained sums on the blackboard. Then every integer from 1 to ⌊ (2n^2)/(9) ⌋ has to be written on the blackboard at least once.
It is guaranteed that such an arrangement exists.
Input
The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of nodes.
Each of the next n-1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), meaning that there is an edge between nodes u and v. It is guaranteed that these edges form a tree.
Output
Output n-1 lines, each of form u v x (0 ≤ x ≤ 10^6), which will mean that you wrote number x on the edge between u, v.
Set of edges (u, v) has to coincide with the set of edges of the input graph, but you can output edges in any order. You can also output ends of edges in an order different from the order in input.
Examples
Input
3
2 3
2 1
Output
3 2 1
1 2 2
Input
4
2 4
2 3
2 1
Output
4 2 1
3 2 2
1 2 3
Input
5
1 2
1 3
1 4
2 5
Output
2 1 1
5 2 1
3 1 3
4 1 6
Note
In the first example, distance between nodes 1 and 2 is equal to 2, between nodes 2 and 3 to 1, between 1 and 3 to 3.
In the third example, numbers from 1 to 9 (inclusive) will be written on the blackboard, while we need just from 1 to 5 to pass the test. | instruction | 0 | 27,493 | 13 | 54,986 |
Tags: constructive algorithms, trees
Correct Solution:
```
import math
n = int(input())
if n == 1:
print()
else:
edge = [list(map(int, input().split())) for i in range(1, n) ]
g = {}
for x, y in edge:
if x not in g:
g[x] = []
if y not in g:
g[y] = []
g[x].append(y)
g[y].append(x)
def find_centroid(g):
p = {}
size = {}
p[1] = -1
Q = [1]
i = 0
while i < len(Q):
u = Q[i]
for v in g[u]:
if p[u] == v: continue
p[v] = u
Q.append(v)
i+=1
for u in Q[::-1]:
size[u] = 1
for v in g[u]:
if p[u] == v:
continue
size[u] += size[v]
cur = 1
n = size[cur]
while True:
max_ = n - size[cur]
ind_ = p[cur]
for v in g[cur]:
if v == p[cur]: continue
if size[v] > max_:
max_ = size[v]
ind_ = v
if max_ <= n // 2:
return cur
cur = ind_
def find_center(g):
d = {}
d[1] = 0
Q = [(1, 0)]
while len(Q) > 0:
u, dis = Q.pop(0)
for v in g[u]:
if v not in d:
d[v] = dis +1
Q.append((v, d[v]))
max_length = -1
s = None
for u, dis in d.items():
if dis > max_length:
max_length = dis
s = u
d = {}
pre = {}
d[s] = 0
Q = [(s, 0)]
while len(Q) > 0:
u, dis = Q.pop(0)
for v in g[u]:
if v not in d:
pre[v] = u
d[v] = dis +1
Q.append((v, d[v]))
max_length = -1
e = None
for u, dis in d.items():
if dis > max_length:
max_length = dis
e = u
route = [e]
while pre[route[-1]] != s:
route.append(pre[route[-1]])
print(route)
return route[len(route) // 2]
root = find_centroid(g)
p = {}
size = {}
Q = [root]
p[root] = -1
i = 0
while i < len(Q):
u = Q[i]
for v in g[u]:
if p[u] == v: continue
p[v] = u
Q.append(v)
i+=1
for u in Q[::-1]:
size[u] = 1
for v in g[u]:
if p[u] == v:
continue
size[u] += size[v]
gr = [(u, size[u]) for u in g[root]]
gr = sorted(gr, key=lambda x:x[1])
thres = math.ceil((n-1) / 3)
sum_ = 0
gr1 = []
gr2 = []
i = 0
while sum_ < thres:
gr1.append(gr[i][0])
sum_ += gr[i][1]
i+=1
while i < len(gr):
gr2.append(gr[i][0])
i+=1
def asign(u, W, ew):
if size[u] == 1:
return
cur = 0
for v in g[u]:
if v == p[u]: continue
first = W[cur]
ew.append((u, v, first))
W_ = [x - first for x in W[cur+1: cur+size[v]]]
asign(v, W_, ew)
cur+=size[v]
a, b = 0, 0
for x in gr1:
a += size[x]
for x in gr2:
b += size[x]
arr_1 = [x for x in range(1, a+1)]
arr_2 = [i*(a+1) for i in range(1, b+1)]
ew = []
cur = 0
for u in gr1:
first = arr_1[cur]
ew.append((root, u, first))
W_ = [x - first for x in arr_1[cur+1:cur+size[u]]]
cur += size[u]
#print(u, W_)
asign(u, W_, ew)
cur = 0
for u in gr2:
first = arr_2[cur]
ew.append((root, u, first))
W_ = [x - first for x in arr_2[cur+1:cur+size[u]]]
cur += size[u]
#print(u, W_)
asign(u, W_, ew)
for u, v, w in ew:
print('{} {} {}'.format(u, v, w))
``` | output | 1 | 27,493 | 13 | 54,987 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with n nodes. You have to write non-negative integers on its edges so that the following condition would be satisfied:
For every two nodes i, j, look at the path between them and count the sum of numbers on the edges of this path. Write all obtained sums on the blackboard. Then every integer from 1 to ⌊ (2n^2)/(9) ⌋ has to be written on the blackboard at least once.
It is guaranteed that such an arrangement exists.
Input
The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of nodes.
Each of the next n-1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), meaning that there is an edge between nodes u and v. It is guaranteed that these edges form a tree.
Output
Output n-1 lines, each of form u v x (0 ≤ x ≤ 10^6), which will mean that you wrote number x on the edge between u, v.
Set of edges (u, v) has to coincide with the set of edges of the input graph, but you can output edges in any order. You can also output ends of edges in an order different from the order in input.
Examples
Input
3
2 3
2 1
Output
3 2 1
1 2 2
Input
4
2 4
2 3
2 1
Output
4 2 1
3 2 2
1 2 3
Input
5
1 2
1 3
1 4
2 5
Output
2 1 1
5 2 1
3 1 3
4 1 6
Note
In the first example, distance between nodes 1 and 2 is equal to 2, between nodes 2 and 3 to 1, between 1 and 3 to 3.
In the third example, numbers from 1 to 9 (inclusive) will be written on the blackboard, while we need just from 1 to 5 to pass the test.
Submitted Solution:
```
import math
n = int(input())
if n == 1:
print()
else:
edge = [list(map(int, input().split())) for _ in range(n-1) ]
g = {}
for x, y in edge:
if x not in g:
g[x] = []
if y not in g:
g[y] = []
g[x].append(y)
g[y].append(x)
def find_center(g):
d = {}
d[1] = 0
Q = [(1, 0)]
while len(Q) > 0:
u, dis = Q.pop(0)
for v in g[u]:
if v not in d:
d[v] = dis +1
Q.append((v, d[v]))
max_length = -1
s = None
for u, dis in d.items():
if dis > max_length:
max_length = dis
s = u
d = {}
pre = {}
d[s] = 0
Q = [(s, 0)]
while len(Q) > 0:
u, dis = Q.pop(0)
for v in g[u]:
if v not in d:
pre[v] = u
d[v] = dis +1
Q.append((v, d[v]))
max_length = -1
e = None
for u, dis in d.items():
if dis > max_length:
max_length = dis
e = u
route = [e]
while pre[route[-1]] != s:
route.append(pre[route[-1]])
return route[len(route) // 2]
root = find_center(g)
p = {}
size = {}
Q = [root]
p[root] = -1
i = 0
while i < len(Q):
u = Q[i]
for v in g[u]:
if p[u] == v: continue
p[v] = u
Q.append(v)
i+=1
for u in Q[::-1]:
size[u] = 1
for v in g[u]:
if p[u] == v:
continue
size[u] += size[v]
gr = [(u, size[u]) for u in g[root]]
gr = sorted(gr, key=lambda x:x[1])
thres = math.ceil((n-1) / 3)
sum_ = 0
gr1 = []
gr2 = []
i = 0
while sum_ < thres:
gr1.append(gr[i][0])
sum_ += gr[i][1]
i+=1
while i < len(gr):
gr2.append(gr[i][0])
i+=1
def asign(u, W, ew):
if size[u] == 1:
return
cur = 0
for v in g[u]:
if v == p[u]: continue
first = W[cur]
ew.append((u, v, first))
W_ = [x - first for x in W[cur+1: cur+size[v]]]
asign(v, W_, ew)
cur+=size[v]
a, b = 0, 0
for x in gr1:
a += size[x]
for x in gr2:
b += size[x]
arr_1 = [x for x in range(1, a+1)]
arr_2 = [i*(a+1) for i in range(1, b+1)]
ew = []
cur = 0
for u in gr1:
first = arr_1[cur]
ew.append((root, u, first))
W_ = [x - first for x in arr_1[cur+1:cur+size[u]]]
cur += size[u]
#print(u, W_)
asign(u, W_, ew)
cur = 0
for u in gr2:
first = arr_2[cur]
ew.append((root, u, first))
W_ = [x - first for x in arr_2[cur+1:cur+size[u]]]
cur += size[u]
#print(u, W_)
asign(u, W_, ew)
for u, v, w in ew:
print('{} {} {}'.format(u, v, w))
``` | instruction | 0 | 27,494 | 13 | 54,988 |
No | output | 1 | 27,494 | 13 | 54,989 |
Provide tags and a correct Python 3 solution for this coding contest problem.
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3.
A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge.
John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it.
Input
A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph.
Output
In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i.
Examples
Input
1
Output
3
011
101
110
Input
10
Output
5
01111
10111
11011
11101
11110 | instruction | 0 | 27,713 | 13 | 55,426 |
Tags: binary search, constructive algorithms, graphs, greedy
Correct Solution:
```
n, k = 0, int(input())
p = [['0'] * 100 for i in range(100)]
while k:
for i in range(n):
if i > k: break
p[n][i] = p[i][n] = '1'
k -= i
n += 1
print(n)
for i in range(n): print(''.join(p[i][:n]))
# Made By Mostafa_Khaled
``` | output | 1 | 27,713 | 13 | 55,427 |
Provide tags and a correct Python 3 solution for this coding contest problem.
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3.
A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge.
John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it.
Input
A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph.
Output
In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i.
Examples
Input
1
Output
3
011
101
110
Input
10
Output
5
01111
10111
11011
11101
11110 | instruction | 0 | 27,714 | 13 | 55,428 |
Tags: binary search, constructive algorithms, graphs, greedy
Correct Solution:
```
# https://codeforces.com/contest/232/problem/A
# WA
def f_3(n):
return n * (n-1) * (n-2) // 6
def f_2(n):
return n * (n-1) // 2
a_3 = [f_3(i) for i in range(100)]
a_2 = [f_2(i) for i in range(100)]
def find_2(x, a):
arr = []
cur = len(a) - 1
while x > 0:
while x < a[cur]:
cur -= 1
arr.append(cur)
x -= a[cur]
return arr
def find_3(x, a):
cur = len(a) - 1
while x < a[cur]:
cur -= 1
x -= a[cur]
return cur, x
def build(x):
base, remain = find_3(x, a_3)
arr = find_2(remain, a_2)
n = base
#print(base, arr)
if len(arr) > 0:
n += len(arr)
m = [[0]*n for _ in range(n)]
for i in range(base):
for j in range(base):
if i == j:
continue
m[i][j] = 1
m[j][i] = 1
for i, x in enumerate(arr):
for j in range(x):
m[base+i][j] = 1
m[j][base+i] = 1
return m
def pr(m):
for i in range(len(m)):
print(''.join([str(x) for x in m[i]]))
k = int(input())
m = build(k)
print(len(m))
pr(m)
``` | output | 1 | 27,714 | 13 | 55,429 |
Provide tags and a correct Python 3 solution for this coding contest problem.
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3.
A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge.
John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it.
Input
A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph.
Output
In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i.
Examples
Input
1
Output
3
011
101
110
Input
10
Output
5
01111
10111
11011
11101
11110 | instruction | 0 | 27,715 | 13 | 55,430 |
Tags: binary search, constructive algorithms, graphs, greedy
Correct Solution:
```
import sys
import math
c=int(input())
Ans=[]
F=[1]
for i in range(1,101):
F.append(F[-1]*i)
for i in range(100):
Ans.append([0]*100)
print(100)
cycles=1
Ans[0][1]=1
Ans[1][0]=1
Ans[1][2]=1
Ans[2][1]=1
Ans[0][2]=1
Ans[2][0]=1
m=3
while(cycles<c):
Ans[0][m]=1
Ans[m][0]=1
inc=1
for j in range(1,m):
Ans[j][m]=1
Ans[m][j]=1
cycles+=inc
inc+=1
if(cycles+inc>c):
break
m+=1
A=""
for i in range(100):
for j in range(100):
A+=str(Ans[i][j])
A+="\n"
sys.stdout.write(A)
``` | output | 1 | 27,715 | 13 | 55,431 |
Provide tags and a correct Python 3 solution for this coding contest problem.
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3.
A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge.
John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it.
Input
A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph.
Output
In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i.
Examples
Input
1
Output
3
011
101
110
Input
10
Output
5
01111
10111
11011
11101
11110 | instruction | 0 | 27,716 | 13 | 55,432 |
Tags: binary search, constructive algorithms, graphs, greedy
Correct Solution:
```
n = 100
g = [set() for i in range(n)]
k = int(input())
ans = 0
flag = False
for l in range(n):
for r in range(l + 1):
if l == r or l in g[r]:
continue
count = 0
for u in range(n):
if u == l or u == r:
continue
if l in g[u] and r in g[u]:
count += 1
if count + ans <= k:
ans += count
g[l].add(r)
g[r].add(l)
if ans == k:
flag = True
break
if flag:
break
ans = [[0 for i in range(n)] for j in range(n)]
print(100)
for i in range(n):
for j in range(n):
if j in g[i]:
ans[i][j] = 1
print(*ans[i], sep='')
``` | output | 1 | 27,716 | 13 | 55,433 |
Provide tags and a correct Python 3 solution for this coding contest problem.
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3.
A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge.
John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it.
Input
A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph.
Output
In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i.
Examples
Input
1
Output
3
011
101
110
Input
10
Output
5
01111
10111
11011
11101
11110 | instruction | 0 | 27,717 | 13 | 55,434 |
Tags: binary search, constructive algorithms, graphs, greedy
Correct Solution:
```
k = int(input())
n = 0
matr = [['0'] * 100 for i in range(100)]
while k:
for i in range(n):
if i > k:
break
matr[n][i] = matr[i][n] = '1'
k -= i
n += 1
print(n)
for i in range(n):
print(''.join(matr[i][:n]))
``` | output | 1 | 27,717 | 13 | 55,435 |
Provide tags and a correct Python 3 solution for this coding contest problem.
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3.
A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge.
John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it.
Input
A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph.
Output
In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i.
Examples
Input
1
Output
3
011
101
110
Input
10
Output
5
01111
10111
11011
11101
11110 | instruction | 0 | 27,718 | 13 | 55,436 |
Tags: binary search, constructive algorithms, graphs, greedy
Correct Solution:
```
n, k = 0, int(input())
p = [['0'] * 100 for i in range(100)]
while k:
for i in range(n):
if i > k: break
p[n][i] = p[i][n] = '1'
k -= i
n += 1
print(n)
for i in range(n): print(''.join(p[i][:n]))
``` | output | 1 | 27,718 | 13 | 55,437 |
Provide tags and a correct Python 3 solution for this coding contest problem.
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3.
A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge.
John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it.
Input
A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph.
Output
In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i.
Examples
Input
1
Output
3
011
101
110
Input
10
Output
5
01111
10111
11011
11101
11110 | instruction | 0 | 27,719 | 13 | 55,438 |
Tags: binary search, constructive algorithms, graphs, greedy
Correct Solution:
```
n = int( input() )
a = []
MAXN = 100
for i in range(MAXN):
a.append( [0]*MAXN )
for i in range(3):
for j in range(3):
if i != j:
a[i][j] = 1
cycles = 1
if cycles != n:
for i in range(3,MAXN):
if cycles == n:
break
a[i][0] = a[0][i] = 1
a[i][1] = a[1][i] = 1
cycles += 1
if cycles == n:
break
how = 2
for j in range(2,i):
if a[i][j] == 1:
continue
if j != i:
if cycles + how <= n:
a[i][j] = a[j][i] = 1
cycles += how
how += 1
if cycles == n:
break
print(MAXN)
for i in range( len(a) ):
for j in a[i]:
print( j, end='')
print()
``` | output | 1 | 27,719 | 13 | 55,439 |
Provide tags and a correct Python 3 solution for this coding contest problem.
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3.
A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge.
John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it.
Input
A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph.
Output
In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i.
Examples
Input
1
Output
3
011
101
110
Input
10
Output
5
01111
10111
11011
11101
11110 | instruction | 0 | 27,720 | 13 | 55,440 |
Tags: binary search, constructive algorithms, graphs, greedy
Correct Solution:
```
start, k = 0, int(input())
lst = [['0'] * 100 for i in range(100)]
while k>0:
for i in range(start):
if i >k:
break
lst[start][i] = lst[i][start] = '1'
k -= i
start += 1
print(start)
for i in range(start):
print(''.join(lst[i][:start]))
``` | output | 1 | 27,720 | 13 | 55,441 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3.
A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge.
John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it.
Input
A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph.
Output
In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i.
Examples
Input
1
Output
3
011
101
110
Input
10
Output
5
01111
10111
11011
11101
11110
Submitted Solution:
```
k = int(input())
p = [['0'] * 100 for j in range(100)]
g = lambda n: n * (n * n - 1) // 6
i = n = 0
while g(n + 1) <= k: n += 1
while i < n + 1:
for j in range(i): p[i][j] = p[j][i] = '1'
i += 1
k -= g(n)
g = lambda n: n * n - n >> 1
while k:
n = 0
while g(n + 1) <= k: n += 1
for j in range(n): p[i][j] = p[j][i] = '1'
k -= g(n)
i += 1
print(i)
for j in range(i): print(''.join(p[j][:i]))
``` | instruction | 0 | 27,721 | 13 | 55,442 |
Yes | output | 1 | 27,721 | 13 | 55,443 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3.
A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge.
John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it.
Input
A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph.
Output
In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i.
Examples
Input
1
Output
3
011
101
110
Input
10
Output
5
01111
10111
11011
11101
11110
Submitted Solution:
```
n = int( input() )
a = []
MAXN = 100
for i in range(MAXN):
a.append( [0]*MAXN )
for i in range(3):
for j in range(3):
if i != j:
a[i][j] = 1
cycles = 1
if cycles != n:
for i in range(3,MAXN):
if cycles == n:
break
a[i][0] = a[0][i] = 1
a[i][1] = a[1][i] = 1
cycles += 1
if cycles == n:
break
how = 2
for j in range(2,i):
if j != i:
if cycles + how <= n:
a[i][j] = a[j][i] = 1
cycles += how
how += 1
if cycles == n:
break
print(MAXN)
for i in range( len(a) ):
for j in a[i]:
print( j, end='')
print()
``` | instruction | 0 | 27,722 | 13 | 55,444 |
Yes | output | 1 | 27,722 | 13 | 55,445 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3.
A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge.
John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it.
Input
A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph.
Output
In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i.
Examples
Input
1
Output
3
011
101
110
Input
10
Output
5
01111
10111
11011
11101
11110
Submitted Solution:
```
n , k = 0 , int(input())
p=[['0']*100 for i in range(100)]
while k:
for i in range(n):
if i>k:
break
p[n][i]=p[i][n]='1'
k=k-i
n+=1
print(n)
for i in range(n): print(''.join(p[i][:n]))
``` | instruction | 0 | 27,723 | 13 | 55,446 |
Yes | output | 1 | 27,723 | 13 | 55,447 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3.
A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge.
John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it.
Input
A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph.
Output
In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i.
Examples
Input
1
Output
3
011
101
110
Input
10
Output
5
01111
10111
11011
11101
11110
Submitted Solution:
```
k = int(input())
p = [['0'] * 100 for j in range(100)]
i, n = 0, 0
g = lambda n: n * (n * n - 1) // 6
while g(n + 1) <= k:
n += 1
while i < n + 1:
for j in range(i):
p[i][j] = p[j][i] = '1'
i += 1
k -= g(n)
g = lambda n: n * (n - 1) // 2
while k:
n = 0
while g(n + 1) <= k:
n += 1
for j in range(n):
p[i][j] = p[j][i] = '1'
k -= g(n)
i += 1
print(i)
for j in range(i):
print(''.join(p[j][:i]))
``` | instruction | 0 | 27,724 | 13 | 55,448 |
Yes | output | 1 | 27,724 | 13 | 55,449 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3.
A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge.
John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it.
Input
A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph.
Output
In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i.
Examples
Input
1
Output
3
011
101
110
Input
10
Output
5
01111
10111
11011
11101
11110
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
from itertools import combinations_with_replacement,permutations
from collections import defaultdict
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# code region
def calc(n):
x = n*(n-1)*(n-2)
x = x//6
return x
k = int(input())
lo,hi = 3,100
while lo<hi:
m = (lo+hi)//2
nodes = calc(m)
if nodes<k:
lo = m
else:
hi = m
if hi-lo==1:
break
if calc(lo)>=k:
m = lo
else:
m = hi
dp = [[0 for i in range(m)]for j in range(m)]
f = 0
for i in range(m):
for j in range(i+1,m):
dp[i][j] = 1
dp[j][i] = 1
for k in range(j+1,m):
dp[j][k] = 1
dp[k][j] = 1
dp[i][k] = 1
dp[k][i] = 1
k-=1
if k==0:
f = 1
break
if f==1:
break
if f==1:
break
print(m)
for i in range(m):
for j in range(m):
print(dp[i][j],end='')
print()
``` | instruction | 0 | 27,725 | 13 | 55,450 |
No | output | 1 | 27,725 | 13 | 55,451 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3.
A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge.
John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it.
Input
A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph.
Output
In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i.
Examples
Input
1
Output
3
011
101
110
Input
10
Output
5
01111
10111
11011
11101
11110
Submitted Solution:
```
def f_3(n):
return n * (n-1) * (n-2) // 6
def f_2(n):
return n * (n-1) // 2
a_3 = [f_3(i) for i in range(100)]
a_2 = [f_2(i) for i in range(100)]
def find_3(x, a):
arr = []
cur = len(a) - 1
while x < a[cur]:
cur -= 1
arr.append(cur)
x -= a[cur]
if x > 0:
cur = 100 - cur
while x < a[cur]:
cur -= 1
arr.append(cur)
x -= a[cur]
return x, arr
def find_2(x, a):
arr = []
cur = len(a) - 1
while x > 0:
while x < a[cur]:
cur -= 1
arr.append(cur)
x -= a[cur]
return arr
def build(arr, remain):
n = sum(arr)
m = [[0]*n for _ in range(n)]
arr = [0] + arr
for i in range(1, len(arr)):
arr[i] += arr[i-1]
for s, e in zip(arr[:-1], arr[1:]):
for i in range(s, e):
for j in range(s, e):
if i == j :
continue
m[i][j] = 1
m[j][i] = 1
arr_2 = find_2(remain, a_2)
base = arr[1]
for i, x in enumerate(arr_2):
for j in range(x):
m[base+i][j] = 1
m[j][base+i] = 1
return m
def pr(m):
for i in range(len(m)):
print(''.join([str(x) for x in m[i]]))
k = int(input())
remain ,arr = find_3(k, a_3)
m = build(arr, remain)
print(len(m))
pr(m)
``` | instruction | 0 | 27,726 | 13 | 55,452 |
No | output | 1 | 27,726 | 13 | 55,453 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3.
A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge.
John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it.
Input
A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph.
Output
In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i.
Examples
Input
1
Output
3
011
101
110
Input
10
Output
5
01111
10111
11011
11101
11110
Submitted Solution:
```
n = int( input() )
a = []
MAXN = 100
for i in range(MAXN):
a.append( [0]*MAXN )
for i in range(3):
for j in range(3):
if i != j:
a[i][j] = 1
cycles = 1
if cycles != n:
for i in range(3,MAXN):
if cycles == n:
break
a[i][0] = a[0][i] = 1
a[i][1] = a[1][i] = 1
cycles += 1
if cycles == n:
break
for j in range(2,MAXN):
a[i][j] = a[j][i] = 1
cycles += 1
if cycles == n:
break
print(MAXN)
for i in range( len(a) ):
for j in a[i]:
print( j, end='')
print()
``` | instruction | 0 | 27,727 | 13 | 55,454 |
No | output | 1 | 27,727 | 13 | 55,455 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3.
A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge.
John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it.
Input
A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph.
Output
In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i.
Examples
Input
1
Output
3
011
101
110
Input
10
Output
5
01111
10111
11011
11101
11110
Submitted Solution:
```
x = input()
memo = {}
for i in x:
if i not in memo:
memo[i] = 1
else:
memo[i] += 1
a = list( zip( memo.values(), memo.keys() ) )
a = sorted(a, key=lambda x: x[0], reverse=True)
def is_prime(n):
if n < 2:
return ( False )
i = 2
while i*i <= n:
if n % i == 0:
return ( False )
i += 1
return ( True )
#print( a )
step = 2
n = len( x )
ans = [ "" ]*n
idx = 0
#print(n)
#print(ans)
step = 1
while True:
how = a[idx][0]
what = a[idx][1]
fl = False
for i in range( 1, n+1 ):
if i % (step+1) == 0:
ans[i-1] += what
how -= 1
fl = True
if how == 0:
break
if fl == False:
for i in range( 1, n+1 ):
ans[i-1] += what
how -= 1
fl = True
if how == 0:
break
a[idx] = ( how, a[idx][1] )
#print(idx)
#print(a)
if how == 0:
idx += 1
step += 1
step = max( 1, step%n)
if idx >= len(a):
break
ret = ""
#print( ans )
for i in ans:
if i != '':
ret += i
print( ret )
#print( a )
``` | instruction | 0 | 27,728 | 13 | 55,456 |
No | output | 1 | 27,728 | 13 | 55,457 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tree is a connected acyclic graph. Suppose you are given a tree consisting of n vertices. The vertex of this tree is called centroid if the size of each connected component that appears if this vertex is removed from the tree doesn't exceed <image>.
You are given a tree of size n and can perform no more than one edge replacement. Edge replacement is the operation of removing one edge from the tree (without deleting incident vertices) and inserting one new edge (without adding new vertices) in such a way that the graph remains a tree. For each vertex you have to determine if it's possible to make it centroid by performing no more than one edge replacement.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 400 000) — the number of vertices in the tree. Each of the next n - 1 lines contains a pair of vertex indices ui and vi (1 ≤ ui, vi ≤ n) — endpoints of the corresponding edge.
Output
Print n integers. The i-th of them should be equal to 1 if the i-th vertex can be made centroid by replacing no more than one edge, and should be equal to 0 otherwise.
Examples
Input
3
1 2
2 3
Output
1 1 1
Input
5
1 2
1 3
1 4
1 5
Output
1 0 0 0 0
Note
In the first sample each vertex can be made a centroid. For example, in order to turn vertex 1 to centroid one have to replace the edge (2, 3) with the edge (1, 3).
Submitted Solution:
```
#!/usr/bin/python3
class TaskSolver:
__slot__ = ["__numberOfNodes",
"__neighbours",
"__subtreeSize",
"__maxFeasibleCuts"
"__parent"
"__maxCutSize"
"__isCentroid"
"__superTreeCut"
]
def __init__(self, n):
self.__numberOfNodes = int(n)
self.__maxCutSize = n // 2
self.__isCentroid = None
self.__neighbours = {}
for i in range(self.__numberOfNodes):
self.__neighbours[i] = []
self.__read_graph()
def __read_graph(self):
for i in range(self.__numberOfNodes - 1):
a, b = map(lambda x: int(x) - 1, input().split(" "))
self.__neighbours[a].append(b)
self.__neighbours[b].append(a)
def result(self):
if self.__isCentroid is None:
self.__compute_results()
self.__isCentroid = list(map(int, self.__isCentroid))
return self.__isCentroid.copy()
def __compute_results(self):
self.__maxFeasibleCuts = [[0,0]] * self.__numberOfNodes
self.__subtreeSize = [0] * self.__numberOfNodes
self.__parent = [-1] * self.__numberOfNodes
self.__preprocessDFS(0, [False] * self.__numberOfNodes)
self.__isCentroid = [True] * self.__numberOfNodes
self.__superTreeCut = [0] * self.__numberOfNodes
self.__secondDFS(0, [False] * self.__numberOfNodes)
def __preprocessDFS(self, node, isVisited):
isVisited[node] = True
self.__subtreeSize[node] = 1
for child in self.__neighbours[node]:
if not isVisited[child]:
self.__parent[child] = node
self.__preprocessDFS(child, isVisited)
self.__subtreeSize[node] += self.__subtreeSize[child]
self.__maxFeasibleCuts[node] = self.__get_updated_feasible_cuts(node, child)
def __get_updated_feasible_cuts(self, node, child):
maxCuts = self.__maxFeasibleCuts[node].copy()
bestChildCut = self.__maxFeasibleCuts[child][0]
if self.__subtreeSize[child] <= self.__maxCutSize:
bestChildCut = self.__subtreeSize[child]
if maxCuts[0] < bestChildCut:
maxCuts[1] = maxCuts[0]
maxCuts[0] = bestChildCut
elif maxCuts[1] < bestChildCut:
maxCuts[1] = bestChildCut
return maxCuts
def __secondDFS(self, node, isVisited):
isVisited[node] = True
if self.__get_superTree_size(node) - self.__superTreeCut[node] > self.__maxCutSize:
self.__isCentroid[node] = False
for child in self.__neighbours[node]:
if not isVisited[child]:
self.__superTreeCut[child] = self.__get_cut_for_superTree(child)
if self.__subtreeSize[child] - self.__maxFeasibleCuts[child][0] > self.__maxCutSize:
self.__isCentroid[node] = False
self.__secondDFS(child, isVisited)
def __get_cut_for_superTree(self, node):
parent = self.__parent[node]
res = self.__superTreeCut[parent]
if self.__get_superTree_size(parent) <= self.__maxCutSize:
res = self.__get_superTree_size(parent)
# for subtrees of parent
subtreeCuts = self.__maxFeasibleCuts[parent]
if subtreeCuts[0] == self.__maxFeasibleCuts[node][0] or subtreeCuts[0] == self.__subtreeSize[node]:
res = max(res, subtreeCuts[1])
else:
res = max(res, subtreeCuts[0])
return res
def __get_superTree_size(self, node):
return self.__numberOfNodes - self.__subtreeSize[node]
n = int(input())
try:
for res in TaskSolver(n).result():
print(res, end=" ")
print()
except Exception as e:
print(e)
``` | instruction | 0 | 27,926 | 13 | 55,852 |
No | output | 1 | 27,926 | 13 | 55,853 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tree is a connected acyclic graph. Suppose you are given a tree consisting of n vertices. The vertex of this tree is called centroid if the size of each connected component that appears if this vertex is removed from the tree doesn't exceed <image>.
You are given a tree of size n and can perform no more than one edge replacement. Edge replacement is the operation of removing one edge from the tree (without deleting incident vertices) and inserting one new edge (without adding new vertices) in such a way that the graph remains a tree. For each vertex you have to determine if it's possible to make it centroid by performing no more than one edge replacement.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 400 000) — the number of vertices in the tree. Each of the next n - 1 lines contains a pair of vertex indices ui and vi (1 ≤ ui, vi ≤ n) — endpoints of the corresponding edge.
Output
Print n integers. The i-th of them should be equal to 1 if the i-th vertex can be made centroid by replacing no more than one edge, and should be equal to 0 otherwise.
Examples
Input
3
1 2
2 3
Output
1 1 1
Input
5
1 2
1 3
1 4
1 5
Output
1 0 0 0 0
Note
In the first sample each vertex can be made a centroid. For example, in order to turn vertex 1 to centroid one have to replace the edge (2, 3) with the edge (1, 3).
Submitted Solution:
```
class Tree:
def __init__(self, id):
self.son = []
self.f = None
self.idx = None
self.dp0 = 0
self.dp1 = 0
self.sz = 1
self.id = id
n = int(input())
bound = n // 2
ans = [1] * n
def chk(x):
if x > bound:
return 0
return x
def dfs(r, f):
r.f = f
for son in r.son:
if son is r.f:
continue
dfs(son, r)
r.sz += son.sz
mx = max(chk(son.sz), son.dp0)
if mx > r.dp0:
r.idx = son
r.dp0, r.dp1 = (mx, r.dp0)
elif mx > r.dp1:
r.dp1 = mx
def dfs2(r, mx):
if (n - r.sz - mx) > bound:
ans[r.id] = 0
tmx = max(chk(n - r.sz), mx)
for son in r.son:
if son is r.f:
continue
if (son.sz - son.dp0) > bound:
ans[r.id] = 0
if r.idx is son:
dfs2(son, max(tmx, r.dp1))
else:
dfs2(son, max(tmx, r.dp0))
def solve():
arr = [0] * n
for i in range(n):
arr[i] = Tree(i)
for i in range(n-1):
a, b = map(int, input().split())
a -= 1
b -= 1
arr[a].son += [arr[b]]
arr[b].son += [arr[a]]
dfs(arr[0], None)
#if n > 1000:
#for i in range(n):
#ans[i] = 1
#print(' '.join(map(lambda x : str(x), ans)))
#return
#
#if n == 3:
#print('1 1 1')
#elif n == 5:
#print('1 0 0 0 0')
#elif n == 10:
#print('1 1 1 1 1 1 1 1 1 1')
#elif n == 8:
#print('1 1 1 1 1 1 1 0')
#elif n == 13:
#print('1 1 1 0 1 1 0 1 1 0 0 0 0')
dfs2(arr[0], 0)
#print(' '.join(map(lambda x : str(x), ans)))
file = open('my.out', 'w')
file.write(' '.join(map(lambda x : str(x), ans)))
file.write('\n')
file.close()
solve()
``` | instruction | 0 | 27,927 | 13 | 55,854 |
No | output | 1 | 27,927 | 13 | 55,855 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tree is a connected acyclic graph. Suppose you are given a tree consisting of n vertices. The vertex of this tree is called centroid if the size of each connected component that appears if this vertex is removed from the tree doesn't exceed <image>.
You are given a tree of size n and can perform no more than one edge replacement. Edge replacement is the operation of removing one edge from the tree (without deleting incident vertices) and inserting one new edge (without adding new vertices) in such a way that the graph remains a tree. For each vertex you have to determine if it's possible to make it centroid by performing no more than one edge replacement.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 400 000) — the number of vertices in the tree. Each of the next n - 1 lines contains a pair of vertex indices ui and vi (1 ≤ ui, vi ≤ n) — endpoints of the corresponding edge.
Output
Print n integers. The i-th of them should be equal to 1 if the i-th vertex can be made centroid by replacing no more than one edge, and should be equal to 0 otherwise.
Examples
Input
3
1 2
2 3
Output
1 1 1
Input
5
1 2
1 3
1 4
1 5
Output
1 0 0 0 0
Note
In the first sample each vertex can be made a centroid. For example, in order to turn vertex 1 to centroid one have to replace the edge (2, 3) with the edge (1, 3).
Submitted Solution:
```
#!/usr/bin/python3
class TaskSolver:
__slot__ = ["__numberOfNodes",
"__neighbours",
"__subtreeSize",
"__maxFeasibleCuts"
"__parent"
"__maxCutSize"
"__isCentroid"
"__superTreeCut"
]
def __init__(self, n):
self.__numberOfNodes = int(n)
self.__maxCutSize = n // 2
self.__isCentroid = None
self.__neighbours = {}
for i in range(self.__numberOfNodes):
self.__neighbours[i] = []
self.__read_graph()
def __read_graph(self):
for i in range(self.__numberOfNodes - 1):
a, b = map(lambda x: int(x) - 1, input().split(" "))
self.__neighbours[a].append(b)
self.__neighbours[b].append(a)
def result(self):
if self.__isCentroid is None:
self.__compute_results()
self.__isCentroid = list(map(int, self.__isCentroid))
return self.__isCentroid.copy()
def __compute_results(self):
self.__maxFeasibleCuts = [[0,0]] * self.__numberOfNodes
self.__subtreeSize = [0] * self.__numberOfNodes
self.__parent = [-1] * self.__numberOfNodes
self.__preprocessDFS(0, [False] * self.__numberOfNodes)
self.__isCentroid = [True] * self.__numberOfNodes
self.__superTreeCut = [0] * self.__numberOfNodes
self.__secondDFS(0, [False] * self.__numberOfNodes)
def __preprocessDFS(self, node, isVisited):
isVisited[node] = True
self.__subtreeSize[node] = 1
for child in self.__neighbours[node]:
if not isVisited[child]:
self.__parent[child] = node
self.__preprocessDFS(child, isVisited)
self.__subtreeSize[node] += self.__subtreeSize[child]
self.__maxFeasibleCuts[node] = self.__get_updated_feasible_cuts(node, child)
def __get_updated_feasible_cuts(self, node, child):
maxCuts = self.__maxFeasibleCuts[node].copy()
bestChildCut = self.__maxFeasibleCuts[child][0]
if self.__subtreeSize[child] <= self.__maxCutSize:
bestChildCut = self.__subtreeSize[child]
if maxCuts[0] < bestChildCut:
maxCuts[1] = maxCuts[0]
maxCuts[0] = bestChildCut
elif maxCuts[1] < bestChildCut:
maxCuts[1] = bestChildCut
return maxCuts
def __secondDFS(self, node, isVisited):
isVisited[node] = True
if self.__get_superTree_size(node) - self.__superTreeCut[node] > self.__maxCutSize:
self.__isCentroid[node] = False
for child in self.__neighbours[node]:
if not isVisited[child]:
self.__superTreeCut[child] = self.__get_cut_for_superTree(child)
if self.__subtreeSize[child] - self.__maxFeasibleCuts[child][0] > self.__maxCutSize:
self.__isCentroid[node] = False
self.__secondDFS(child, isVisited)
def __get_cut_for_superTree(self, node):
parent = self.__parent[node]
res = self.__superTreeCut[parent]
if self.__get_superTree_size(parent) <= self.__maxCutSize:
res = self.__get_superTree_size(parent)
# for subtrees of parent
subtreeCuts = self.__maxFeasibleCuts[parent]
if subtreeCuts[0] == self.__maxFeasibleCuts[node][0]:
res = max(res, subtreeCuts[1])
else:
res = max(res, subtreeCuts[0])
return res
def __get_superTree_size(self, node):
return self.__numberOfNodes - self.__subtreeSize[node]
n = int(input())
for res in TaskSolver(n).result():
print(res, end=" ")
print()
``` | instruction | 0 | 27,928 | 13 | 55,856 |
No | output | 1 | 27,928 | 13 | 55,857 |
Provide a correct Python 3 solution for this coding contest problem.
We have N points numbered 1 to N arranged in a line in this order.
Takahashi decides to make an undirected graph, using these points as the vertices. In the beginning, the graph has no edge. Takahashi will do M operations to add edges in this graph. The i-th operation is as follows:
* The operation uses integers L_i and R_i between 1 and N (inclusive), and a positive integer C_i. For every pair of integers (s, t) such that L_i \leq s < t \leq R_i, add an edge of length C_i between Vertex s and Vertex t.
The integers L_1, ..., L_M, R_1, ..., R_M, C_1, ..., C_M are all given as input.
Takahashi wants to solve the shortest path problem in the final graph obtained. Find the length of the shortest path from Vertex 1 to Vertex N in the final graph.
Constraints
* 2 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq L_i < R_i \leq N
* 1 \leq C_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N M
L_1 R_1 C_1
:
L_M R_M C_M
Output
Print the length of the shortest path from Vertex 1 to Vertex N in the final graph. If there is no shortest path, print `-1` instead.
Examples
Input
4 3
1 3 2
2 4 3
1 4 6
Output
5
Input
4 2
1 2 1
3 4 2
Output
-1
Input
10 7
1 5 18
3 4 8
1 3 5
4 7 10
5 9 8
6 10 5
8 10 3
Output
28 | instruction | 0 | 28,048 | 13 | 56,096 |
"Correct Solution:
```
N, M = map(int, input().split())
LRC = sorted([list(map(int, input().split())) for i in range(M)])
inf = float('inf')
dp = [inf] * (N+1)
dp[1] = 0
for l, r, c in LRC:
for i in range(r, l, -1):
if dp[i] > dp[l]+c:
dp[i] = dp[l]+c
else:
break
if dp[-1] < inf:
print(int(dp[-1]))
else:
print(-1)
``` | output | 1 | 28,048 | 13 | 56,097 |
Provide a correct Python 3 solution for this coding contest problem.
We have N points numbered 1 to N arranged in a line in this order.
Takahashi decides to make an undirected graph, using these points as the vertices. In the beginning, the graph has no edge. Takahashi will do M operations to add edges in this graph. The i-th operation is as follows:
* The operation uses integers L_i and R_i between 1 and N (inclusive), and a positive integer C_i. For every pair of integers (s, t) such that L_i \leq s < t \leq R_i, add an edge of length C_i between Vertex s and Vertex t.
The integers L_1, ..., L_M, R_1, ..., R_M, C_1, ..., C_M are all given as input.
Takahashi wants to solve the shortest path problem in the final graph obtained. Find the length of the shortest path from Vertex 1 to Vertex N in the final graph.
Constraints
* 2 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq L_i < R_i \leq N
* 1 \leq C_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N M
L_1 R_1 C_1
:
L_M R_M C_M
Output
Print the length of the shortest path from Vertex 1 to Vertex N in the final graph. If there is no shortest path, print `-1` instead.
Examples
Input
4 3
1 3 2
2 4 3
1 4 6
Output
5
Input
4 2
1 2 1
3 4 2
Output
-1
Input
10 7
1 5 18
3 4 8
1 3 5
4 7 10
5 9 8
6 10 5
8 10 3
Output
28 | instruction | 0 | 28,049 | 13 | 56,098 |
"Correct Solution:
```
import sys
import heapq
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
INF = 10**20
N, M = map(int, input().split())
G = [[]for i in range(N)]
for i in range(1, N):
G[i].append([i-1, 0])
for i in range(M):
L, R, C = map(int, input().split())
G[L-1].append([R-1, C])
S = 0
def dijkstra(N, S):
d = [INF for i in range(N)]
que = []
d[S] = 0
heapq.heappush(que, [0, S])
while not(len(que) == 0):
q = heapq.heappop(que)
ver = q[1] # ノード
dis = q[0] # 過去に更新された最短距離
# vまで2番目に短い距離(最新) < 過去最短距離 の時、
# キューから取り出した過去のものを無視する
if d[ver] < dis:
continue
# 隣接リストに対してループ
for i in range(len(G[ver])):
e = G[ver][i]
if d[e[0]] > d[ver] + e[1]:
d[e[0]] = d[ver] + e[1]
heapq.heappush(que, [d[e[0]], e[0]])
return d[N-1]
ans = dijkstra(N, S)
if ans == INF:
print(-1)
else:
print(dijkstra(N, S))
``` | output | 1 | 28,049 | 13 | 56,099 |
Provide a correct Python 3 solution for this coding contest problem.
We have N points numbered 1 to N arranged in a line in this order.
Takahashi decides to make an undirected graph, using these points as the vertices. In the beginning, the graph has no edge. Takahashi will do M operations to add edges in this graph. The i-th operation is as follows:
* The operation uses integers L_i and R_i between 1 and N (inclusive), and a positive integer C_i. For every pair of integers (s, t) such that L_i \leq s < t \leq R_i, add an edge of length C_i between Vertex s and Vertex t.
The integers L_1, ..., L_M, R_1, ..., R_M, C_1, ..., C_M are all given as input.
Takahashi wants to solve the shortest path problem in the final graph obtained. Find the length of the shortest path from Vertex 1 to Vertex N in the final graph.
Constraints
* 2 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq L_i < R_i \leq N
* 1 \leq C_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N M
L_1 R_1 C_1
:
L_M R_M C_M
Output
Print the length of the shortest path from Vertex 1 to Vertex N in the final graph. If there is no shortest path, print `-1` instead.
Examples
Input
4 3
1 3 2
2 4 3
1 4 6
Output
5
Input
4 2
1 2 1
3 4 2
Output
-1
Input
10 7
1 5 18
3 4 8
1 3 5
4 7 10
5 9 8
6 10 5
8 10 3
Output
28 | instruction | 0 | 28,050 | 13 | 56,100 |
"Correct Solution:
```
from heapq import heappush, heappop
INF = float("inf")
N, M, *LRC = map(int, open(0).read().split())
E = [[] for _ in range(N)]
for i in range(N - 1):
E[i + 1].append((i, 0))
for l, r, c in zip(*[iter(LRC)] * 3):
E[l - 1].append((r - 1, c))
D = [INF] * N
D[0] = 0
Q = [0]
while Q:
t = heappop(Q)
dist, cur = divmod(t, N)
for nxt, cost in E[cur]:
cand = dist + cost
if D[nxt] > cand:
D[nxt] = cand
heappush(Q, cand * N + nxt)
print(-1 if D[N - 1] == INF else D[N - 1])
``` | output | 1 | 28,050 | 13 | 56,101 |
Provide a correct Python 3 solution for this coding contest problem.
We have N points numbered 1 to N arranged in a line in this order.
Takahashi decides to make an undirected graph, using these points as the vertices. In the beginning, the graph has no edge. Takahashi will do M operations to add edges in this graph. The i-th operation is as follows:
* The operation uses integers L_i and R_i between 1 and N (inclusive), and a positive integer C_i. For every pair of integers (s, t) such that L_i \leq s < t \leq R_i, add an edge of length C_i between Vertex s and Vertex t.
The integers L_1, ..., L_M, R_1, ..., R_M, C_1, ..., C_M are all given as input.
Takahashi wants to solve the shortest path problem in the final graph obtained. Find the length of the shortest path from Vertex 1 to Vertex N in the final graph.
Constraints
* 2 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq L_i < R_i \leq N
* 1 \leq C_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N M
L_1 R_1 C_1
:
L_M R_M C_M
Output
Print the length of the shortest path from Vertex 1 to Vertex N in the final graph. If there is no shortest path, print `-1` instead.
Examples
Input
4 3
1 3 2
2 4 3
1 4 6
Output
5
Input
4 2
1 2 1
3 4 2
Output
-1
Input
10 7
1 5 18
3 4 8
1 3 5
4 7 10
5 9 8
6 10 5
8 10 3
Output
28 | instruction | 0 | 28,051 | 13 | 56,102 |
"Correct Solution:
```
#設定
import sys
input = sys.stdin.buffer.readline
INF = float("inf")
#ライブラリインポート
from collections import defaultdict
from heapq import heappop, heappush
#入力受け取り
def getlist():
return list(map(int, input().split()))
class Graph(object):
def __init__(self):
self.graph = defaultdict(list)
def __len__(self):
return len(self.graph)
def add_edge(self, a, b, w):
self.graph[a].append((b, w))
def get_nodes(self):
return self.graph.keys()
class Dijkstra(object):
def __init__(self, graph, s):
self.g = graph.graph
self.dist = defaultdict(lambda: INF)
self.dist[s] = 0
self.prev = defaultdict(lambda: None)
self.Q = []
heappush(self.Q, (self.dist[s], s))
while self.Q:
dist_u, u = heappop(self.Q)
if self.dist[u] < dist_u:
continue
for v, w in self.g[u]:
alt = dist_u + w
if self.dist[v] > alt:
self.dist[v] = alt
self.prev[v] = u
heappush(self.Q, (alt, v))
#処理内容
def main():
N, M = getlist()
G = Graph()
for i in range(M):
L, R, C = getlist()
G.add_edge(L - 1, R - 1, C)
for i in range(N - 1):
G.add_edge(i + 1, i, 0)
D = Dijkstra(G, 0)
if D.dist[N - 1] == INF:
print(-1)
else:
print(D.dist[N - 1])
if __name__ == '__main__':
main()
``` | output | 1 | 28,051 | 13 | 56,103 |
Provide a correct Python 3 solution for this coding contest problem.
We have N points numbered 1 to N arranged in a line in this order.
Takahashi decides to make an undirected graph, using these points as the vertices. In the beginning, the graph has no edge. Takahashi will do M operations to add edges in this graph. The i-th operation is as follows:
* The operation uses integers L_i and R_i between 1 and N (inclusive), and a positive integer C_i. For every pair of integers (s, t) such that L_i \leq s < t \leq R_i, add an edge of length C_i between Vertex s and Vertex t.
The integers L_1, ..., L_M, R_1, ..., R_M, C_1, ..., C_M are all given as input.
Takahashi wants to solve the shortest path problem in the final graph obtained. Find the length of the shortest path from Vertex 1 to Vertex N in the final graph.
Constraints
* 2 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq L_i < R_i \leq N
* 1 \leq C_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N M
L_1 R_1 C_1
:
L_M R_M C_M
Output
Print the length of the shortest path from Vertex 1 to Vertex N in the final graph. If there is no shortest path, print `-1` instead.
Examples
Input
4 3
1 3 2
2 4 3
1 4 6
Output
5
Input
4 2
1 2 1
3 4 2
Output
-1
Input
10 7
1 5 18
3 4 8
1 3 5
4 7 10
5 9 8
6 10 5
8 10 3
Output
28 | instruction | 0 | 28,052 | 13 | 56,104 |
"Correct Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
n,m = map(int,readline().split())
chk = []
for i in range(m):
l,r,c = map(int,readline().split())
chk.append((l-1,r-1,c))
chk.sort()
class SegmentTree:
def __init__(self, n, ele, segfun):
self.ide_ele = ele
self.segfun = segfun
self.n = n
self.N0 = 1 << n.bit_length()
self.data = [self.ide_ele] * (self.N0 * 2)
def update(self, l, r, val):
l += self.N0
r += self.N0
while l < r:
if l & 1:
self.data[l] = self.segfun(self.data[l], val)
l += 1
if r & 1:
self.data[r - 1] = self.segfun(self.data[r - 1], val)
r -= 1
l //= 2
r //= 2
def query(self, i):
i += len(self.data) // 2
ret = self.data[i]
while i > 0:
i //= 2
ret = self.segfun(ret, self.data[i])
return ret
S = SegmentTree(n,10**14,lambda a,b: min(a,b))
S.update(0,1,0)
for l,r,c in chk:
a = S.query(l)
S.update(l,r+1,a+c)
ans = S.query(n-1)
if ans == 10**14:
print(-1)
else:
print(ans)
``` | output | 1 | 28,052 | 13 | 56,105 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.