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 |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Chris is participating in a graph cutting contest. He's a pro. The time has come to test his skills to the fullest.
Chris is given a simple undirected connected graph with n vertices (numbered from 1 to n) and m edges. The problem is to cut it into edge-distinct paths of length 2. Formally, Chris has to partition all edges of the graph into pairs in such a way that the edges in a single pair are adjacent and each edge must be contained in exactly one pair.
For example, the figure shows a way Chris can cut a graph. The first sample test contains the description of this graph.
<image>
You are given a chance to compete with Chris. Find a way to cut the given graph or determine that it is impossible!
Input
The first line of input contains two space-separated integers n and m (1 ≤ n, m ≤ 105), the number of vertices and the number of edges in the graph. The next m lines contain the description of the graph's edges. The i-th line contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), the numbers of the vertices connected by the i-th edge. It is guaranteed that the given graph is simple (without self-loops and multi-edges) and connected.
Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
Output
If it is possible to cut the given graph into edge-distinct paths of length 2, output <image> lines. In the i-th line print three space-separated integers xi, yi and zi, the description of the i-th path. The graph should contain this path, i.e., the graph should contain edges (xi, yi) and (yi, zi). Each edge should appear in exactly one path of length 2. If there are multiple solutions, output any of them.
If it is impossible to cut the given graph, print "No solution" (without quotes).
Examples
Input
8 12
1 2
2 3
3 4
4 1
1 3
2 4
3 5
3 6
5 6
6 7
6 8
7 8
Output
1 2 4
1 3 2
1 4 3
5 3 6
5 6 8
6 7 8
Input
3 3
1 2
2 3
3 1
Output
No solution
Input
3 2
1 2
2 3
Output
1 2 3 | instruction | 0 | 10,326 | 13 | 20,652 |
Tags: dfs and similar, graphs
Correct Solution:
```
import sys
input = sys.stdin.readline
print = sys.stdout.write
def get_input():
n, m = [int(x) for x in input().split(' ')]
graph = [[] for _ in range(n + 1)]
for _ in range(m):
c1, c2 = [int(x) for x in input().split(' ')]
graph[c1].append(c2)
graph[c2].append(c1)
if m % 2 != 0:
print("No solution")
exit(0)
return graph
def dfs(graph):
n = len(graph)
w = [0] * n
pi = [None] * n
visited = [False] * n
finished = [False] * n
adjacency = [[] for _ in range(n)]
stack = [1]
while stack:
current_node = stack[-1]
if visited[current_node]:
stack.pop()
if finished[current_node]:
w[current_node] = 0
continue
# print(current_node, adjacency[current_node])
finished[current_node] = True
unpair = []
for adj in adjacency[current_node]:
if w[adj] == 0:
# print('unpaired ->', adj, w[adj])
unpair.append(adj)
else:
print(' '.join([str(current_node), str(adj), str(w[adj]), '\n']))
while len(unpair) > 1:
print(' '.join([str(unpair.pop()), str(current_node), str(unpair.pop()), '\n']))
w[current_node] = unpair.pop() if unpair else 0
continue
visited[current_node] = True
not_blocked_neighbors = [x for x in graph[current_node] if not visited[x]]
stack += not_blocked_neighbors
adjacency[current_node] = not_blocked_neighbors
# print('stack:', stack, current_node)
# def recursive_dfs(graph):
# n = len(graph)
# visited = [False] * n
# recursive_dfs_visit(graph, 1, visited)
# def recursive_dfs_visit(graph, root, visited):
# unpair = []
# visited[root] = True
# adjacency = [x for x in graph[root] if not visited[x]]
# for adj in adjacency:
# w = recursive_dfs_visit(graph, adj, visited)
# if w == 0:
# unpair.append(adj)
# else:
# print(' '.join([str(root), str(adj), str(w), '\n']))
# while len(unpair) > 1:
# print(' '.join([str(unpair.pop()), str(root), str(unpair.pop()), '\n']))
# if unpair:
# return unpair.pop()
# return 0
if __name__ == "__main__":
graph = get_input()
dfs(graph)
``` | output | 1 | 10,326 | 13 | 20,653 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Chris is participating in a graph cutting contest. He's a pro. The time has come to test his skills to the fullest.
Chris is given a simple undirected connected graph with n vertices (numbered from 1 to n) and m edges. The problem is to cut it into edge-distinct paths of length 2. Formally, Chris has to partition all edges of the graph into pairs in such a way that the edges in a single pair are adjacent and each edge must be contained in exactly one pair.
For example, the figure shows a way Chris can cut a graph. The first sample test contains the description of this graph.
<image>
You are given a chance to compete with Chris. Find a way to cut the given graph or determine that it is impossible!
Input
The first line of input contains two space-separated integers n and m (1 ≤ n, m ≤ 105), the number of vertices and the number of edges in the graph. The next m lines contain the description of the graph's edges. The i-th line contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), the numbers of the vertices connected by the i-th edge. It is guaranteed that the given graph is simple (without self-loops and multi-edges) and connected.
Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
Output
If it is possible to cut the given graph into edge-distinct paths of length 2, output <image> lines. In the i-th line print three space-separated integers xi, yi and zi, the description of the i-th path. The graph should contain this path, i.e., the graph should contain edges (xi, yi) and (yi, zi). Each edge should appear in exactly one path of length 2. If there are multiple solutions, output any of them.
If it is impossible to cut the given graph, print "No solution" (without quotes).
Examples
Input
8 12
1 2
2 3
3 4
4 1
1 3
2 4
3 5
3 6
5 6
6 7
6 8
7 8
Output
1 2 4
1 3 2
1 4 3
5 3 6
5 6 8
6 7 8
Input
3 3
1 2
2 3
3 1
Output
No solution
Input
3 2
1 2
2 3
Output
1 2 3 | instruction | 0 | 10,327 | 13 | 20,654 |
Tags: dfs and similar, graphs
Correct Solution:
```
import sys
input = sys.stdin.readline
print = sys.stdout.write
def get_input():
n, m = [int(x) for x in input().split(' ')]
graph = [[] for _ in range(n + 1)]
for _ in range(m):
c1, c2 = [int(x) for x in input().split(' ')]
graph[c1].append(c2)
graph[c2].append(c1)
if m % 2 != 0:
print("No solution")
exit(0)
return graph
def partitions_bottom_up(graph):
n = len(graph)
w = [0] * n
pi = [None] * n
visited = [False] * n
finished = [False] * n
adjacency = [[] for _ in range(n)]
stack = [1]
while stack:
current_node = stack[-1]
if visited[current_node]:
stack.pop()
if finished[current_node]:
w[current_node] = 0
continue
finished[current_node] = True
unpair = []
for adj in adjacency[current_node]:
if w[adj] == 0:
unpair.append(adj)
else:
print(' '.join([str(current_node), str(adj), str(w[adj]), '\n']))
while len(unpair) > 1:
print(' '.join([str(unpair.pop()), str(current_node), str(unpair.pop()), '\n']))
w[current_node] = unpair.pop() if unpair else 0
continue
visited[current_node] = True
not_blocked_neighbors = [x for x in graph[current_node] if not visited[x]]
stack += not_blocked_neighbors
adjacency[current_node] = not_blocked_neighbors
def partitions_top_down(graph):
n = len(graph)
visited = [False] * n
for node in range(1, n):
if not visited[node]:
prev_node = None
current_node = node
while current_node is not None:
visited[current_node] = True
leafs = [prev_node] if prev_node is not None else []
adjacency = []
for adj in graph[current_node]:
if not visited[adj]:
if len(graph[adj]) == 1:
leafs.append(adj)
else:
adjacency.append(adj)
while len(leafs) > 1:
print(' '.join([str(leafs.pop()), str(current_node), str(leafs.pop()), '\n']))
if leafs:
adjacency.append(leafs.pop())
while len(adjacency) > 1:
print(' '.join([str(adjacency.pop()), str(current_node), str(adjacency.pop()), '\n']))
if adjacency:
current_node, prev_node = adjacency.pop(), current_node
else:
current_node = None
if __name__ == "__main__":
graph = get_input()
partitions_bottom_up(graph)
``` | output | 1 | 10,327 | 13 | 20,655 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example. | instruction | 0 | 10,527 | 13 | 21,054 |
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
import sys
from math import sqrt, gcd, ceil, log
from bisect import bisect, bisect_left
from collections import defaultdict, Counter, deque
from heapq import heapify, heappush, heappop
inp = sys.stdin.readline
read = lambda: list(map(int, inp().strip().split()))
# sys.setrecursionlimit(10**3)
def main():
n, m = read()
graph = defaultdict(list)
for i in range(m):
u,v = read()
graph[u].append(v)
graph[v].append(u)
visited = [0]*(n+1)
# def dfs(node):
# visited[node] = 1
# f = (len(graph[node]) == 2)
# for i in graph[node]:
# very good probelm
# if not visited[i]:
# f &= dfs(i)
# # else:
# # return(f)
# return(f)
ans = 0
# print("*******")
for i in range(1, n+1):
if not visited[i]:
f = (len(graph[i]) == 2)
stack = [i]
while stack:
elem = stack.pop()
visited[elem] = 1
f &= (len(graph[elem]) == 2)
for j in graph[elem]:
if not visited[j]:
stack.append(j)
ans += f
print(ans)
if __name__ == "__main__":
main()
``` | output | 1 | 10,527 | 13 | 21,055 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example. | instruction | 0 | 10,528 | 13 | 21,056 |
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
import bisect
import sys
from collections import deque
input = sys.stdin.readline
def main():
n, m = map(int, input().split())
g = [[] for _ in range(n)]
for _ in range(m):
a, b = map(int, input().split())
g[a-1].append(b-1)
g[b-1].append(a-1)
ans = 0
current = []
used = [False] * n
def bfs(node):
q = deque()
q.append(node)
while q:
node = q.popleft()
if not used[node]:
used[node] = True
current.append(node)
for child in g[node]:
q.append(child)
for v in range(n):
current.clear()
if not used[v]:
bfs(v)
cycle = True
for u in current:
if len(g[u]) != 2:
cycle = False
break
if cycle:
ans += 1
print(ans)
if __name__ == '__main__':
main()
``` | output | 1 | 10,528 | 13 | 21,057 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example. | instruction | 0 | 10,529 | 13 | 21,058 |
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
n, m = map(int, input().split())
graph = [[] for _ in range(n+1)]
for _ in range(m):
a, b = map(int, input().split())
graph[a].append(b)
graph[b].append(a)
to_check = set(i for i in range(n+1) if len(graph[i]) == 2)
cnt = 0
while to_check:
node = to_check.pop()
right, left = graph[node]
while left in to_check:
to_check.remove(left)
v1, v2 = graph[left]
if v1 in to_check:
left = v1
elif v2 in to_check:
left = v2
else:
break
if left == right:
cnt += 1
print(cnt)
``` | output | 1 | 10,529 | 13 | 21,059 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example. | instruction | 0 | 10,530 | 13 | 21,060 |
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
from sys import setrecursionlimit
setrecursionlimit(100000)
from collections import deque
nV, nE = map(int, input().split())
g = [[] for _ in range(nV)]
for _ in range(nE):
u, v = map(lambda x: int(x) - 1, input().split())
g[u].append(v)
g[v].append(u)
def bfs(v):
visited[v] = True
q = deque([v])
res = True
while q:
cur = q.pop()
res &= len(g[cur]) == 2
for to in g[cur]:
if not visited[to]:
visited[to] = True
q.appendleft(to)
return res
def dfs(v):
visited[v] = True
res = len(g[v]) == 2
for to in g[v]:
if not visited[to]:
res &= dfs(to)
return res
visited = [False] * nV
ret = 0
for v in range(nV):
if not visited[v]:
ret += bfs(v)
print(ret)
``` | output | 1 | 10,530 | 13 | 21,061 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example. | instruction | 0 | 10,531 | 13 | 21,062 |
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
from sys import stdin,stdout
from collections import Counter
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 DFS(n):
v[n]=True
stack=[n]
p=set()
while stack:
a=stack.pop()
p.add(len(d[a]))
for i in d[a]:
if i==par[a]:
continue
else:
if not v[i]:
v[i]=True
stack.append(i)
par[i]=a
return p=={2}
n,m=mp()
d={i:[] for i in range(1,n+1)}
for i in range(m):
a,b=mp()
d[a].append(b)
d[b].append(a)
v=[False for i in range(n+1)]
ans=0
par=[-1 for i in range(n+1)]
for i in range(1,n+1):
if not v[i]:
cycle=DFS(i)
if cycle:
ans+=1
pr(ans)
``` | output | 1 | 10,531 | 13 | 21,063 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example. | instruction | 0 | 10,532 | 13 | 21,064 |
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
from sys import stdin
from collections import defaultdict, deque
import io
def find_cycle(graph, visited, node):
stack = deque()
stack.append((node, None))
cycle = False
while stack:
(node, parent) = stack.pop()
if node in visited:
cycle = True
else:
stack.extend((child, node) for child in graph[node] if child != parent)
visited.add(node)
return cycle
def cycliccomps(graph):
visited = set()
result = 0
for node in graph:
if node in visited or len(graph[node]) == 2:
continue
find_cycle(graph, visited, node)
for node in graph:
if node in visited:
continue
if find_cycle(graph, visited, node):
result += 1
return result
# input = io.StringIO("""17 15
# 1 8
# 1 12
# 5 11
# 11 9
# 9 15
# 15 5
# 4 13
# 3 13
# 4 3
# 10 16
# 7 10
# 16 7
# 14 3
# 14 4
# 17 6""")
input = stdin
input.readline()
graph = defaultdict(list)
for line in input:
(n1, n2) = line.split()
graph[int(n1)].append(int(n2))
graph[int(n2)].append(int(n1))
print(cycliccomps(graph))
``` | output | 1 | 10,532 | 13 | 21,065 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example. | instruction | 0 | 10,533 | 13 | 21,066 |
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
from sys import stdin
input=stdin.readline
R=lambda:map(int,input().split())
I=lambda:int(input())
S=lambda:input().rstrip('\n')
n,m=R()
v=[[] for i in range(n)]
for i in range(m):
a,b=R()
v[a-1]+=b-1,
v[b-1]+=a-1,
vl=[len(v[i]) for i in range(n)]
vst=[0]*n
ans=0
for i in range(n):
if vst[i]:continue
flg=1
stack=[i]
vst[i]=1
if vl[i]!=2:flg=0
while stack:
p=stack.pop()
for el in v[p]:
if not vst[el]:
vst[el]=1
stack+=el,
if vl[el]!=2:flg=0
if flg:ans+=1
print(ans)
``` | output | 1 | 10,533 | 13 | 21,067 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example. | instruction | 0 | 10,534 | 13 | 21,068 |
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
import sys,math
from collections import Counter,deque,defaultdict
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return len(self.roots())
def all_group_members(self):
return {r: self.members(r) for r in self.roots()}
n,m = inpl()
uf = UnionFind(n)
g = [[] for _ in range(n)]
for _ in range(m):
a,b = inpl()
a,b = a-1,b-1
uf.union(a,b)
g[a].append(b)
g[b].append(a)
ch = [[] for _ in range(n)]
for i in range(n):
now = uf.find(i)
ch[now].append(i)
res = 0
for i in range(n):
if ch[i] == [] or len(ch) < 3: continue
d = defaultdict(int)
for now in ch[i]:
for x in g[now]:
d[x] += 1
if len(ch[i]) != len(list(d)): continue
for now in ch[i]:
if d[now] != 2:
break
else:
res += 1
print(res)
``` | output | 1 | 10,534 | 13 | 21,069 |
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 graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example.
Submitted Solution:
```
n, m = map(int, input().split())
edges = __import__('collections').defaultdict(list); connected = set()
for _ in range(m):
v1, v2 = map(int, input().split())
connected.add((v1, v2) if v1 < v2 else (v2, v1))
edges[v1].append(v2); edges[v2].append(v1)
components = set(i for i in edges.keys() if len(edges[i]) == 2)
count = 0
while components:
current, last = edges[components.pop()]
while current in components:
components.remove(current)
v1, v2 = edges[current]
contains_v1, contains_v2 = v1 in components, v2 in components
if not contains_v1 and not contains_v2: break
else: current = (v1 if contains_v1 else v2)
if current == last: count += 1
print(count)
``` | instruction | 0 | 10,535 | 13 | 21,070 |
Yes | output | 1 | 10,535 | 13 | 21,071 |
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 graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example.
Submitted Solution:
```
from collections import deque
from sys import stdin
input=stdin.readline
n,m=map(int,input().split())
arr=[[] for i in range(n+1)]
for i in range(m):
u,v=map(int,input().split())
arr[u].append(v)
arr[v].append(u)
vis=[-1]*(n+1)
count=0
for i in range(1,n+1):
if vis[i]==-1:
l=[]
q=deque()
q.append(i)
while len(q)!=0:
x=q.popleft()
l.append(x)
vis[x]=1
for ele in arr[x]:
if vis[ele]==-1:
q.append(ele)
flag=True
for ele in l:
if len(arr[ele])!=2:
flag=False
break
if flag:
count=count+1
print(count)
``` | instruction | 0 | 10,536 | 13 | 21,072 |
Yes | output | 1 | 10,536 | 13 | 21,073 |
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 graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example.
Submitted Solution:
```
def connected_components(neighbors):
seen = set()
def component(node):
nodes = set([node])
while nodes:
node = nodes.pop()
seen.add(node)
nodes |= neighbors[node] - seen
yield node
for node in neighbors:
if node not in seen:
yield component(node)
from collections import defaultdict
graph = defaultdict(set)
n,m = map(int,input().split())
for _ in range(m):
u,v = map(int,input().split())
graph[u].add(v)
graph[v].add(u)
total = 0
for component in connected_components(graph):
nodes = list(component)
size = len(nodes)
seen = set()
current = nodes[0]
while len(seen) < size:
choice = list(graph[current])
if len(choice) != 2:break
seen.add(current)
possible = [c for c in choice if c not in seen]
if not possible: break
current = possible[0]
if len(seen) == size:
total+=1
print (total)
``` | instruction | 0 | 10,537 | 13 | 21,074 |
Yes | output | 1 | 10,537 | 13 | 21,075 |
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 graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example.
Submitted Solution:
```
# the iterative approach to grpah traversal was required
# generate graph using a dictionary
graph = {}
vert,edge = map(int,input().split())
reached = set()
for _ in range(edge):
a,b = map(int,input().split())
if a not in graph.keys():
graph.update({a:[b]})
else: graph[a].append(b)
if b not in graph.keys():
graph.update({b:[a]})
else: graph[b].append(a)
# cycles have 2 edges, i think
cycle = dict(filter(lambda x: len(x[1]) == 2,graph.items()))
cyc= 0
while cycle:
target = next(iter(cycle))
left,right = cycle.pop(target)
while right in cycle.keys():
l1,r1 = cycle.pop(right)
if r1 in cycle.keys():
right = r1
elif l1 in cycle.keys():
right = l1
else: break
if right == left: cyc +=1
print(cyc)
``` | instruction | 0 | 10,538 | 13 | 21,076 |
Yes | output | 1 | 10,538 | 13 | 21,077 |
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 graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example.
Submitted Solution:
```
from sys import stdin, stdout
count = 0
def find(node):
x = []
while dsu[node] > 0:
x.append(node)
node = dsu[node]
for i in x:
dsu[i] = node
return node
def union(node1, node2):
if node1 != node2:
if dsu[node1] > dsu[node2]:
node1, node2 = node2, node1
dsu[node1] += dsu[node2]
dsu[node2] = node1
else:
if not cycle[node1][0] and cycle[node1][1] == 0:
cycle[node1] = (True, 1)
elif cycle[node1][0] and cycle[node1][1] == 1:
cycle[node1] = (False, 1)
n, m = map(int, stdin.readline().strip().split())
dsu = [-1]*(n+1)
cycle = [(False,0)]*(n+1)
for __ in range(m):
a, b = map(int, stdin.readline().strip().split())
union(find(a), find(b))
for i in range(1, n+1):
if cycle[i][0] and cycle[i][1]==1:
count += 1
stdout.write(f'{count}')
``` | instruction | 0 | 10,539 | 13 | 21,078 |
No | output | 1 | 10,539 | 13 | 21,079 |
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 graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example.
Submitted Solution:
```
n, m = map(int, input().split())
adj = [[] for _ in range(n)]
for _ in range(m):
u, v = map(int, input().split())
u -= 1
v -= 1
adj[u].append(v)
adj[v].append(u)
out = 0
marks = [None for _ in range(n)]
def dfs(v):
stack = [v]
while stack:
v = stack.pop()
if marks[v] is not None:
continue
marks[v] = True
path.append(v)
for j in adj[v]:
stack.append(j)
def graph_cyclic():
if n < 3:
return False
for j in path:
degree = len(adj[j])
if degree % 2 != 0 or degree < (n/2):
return False
return True
cc_cyclic = 0
for i in range(n):
if marks[i] is None:
path = []
dfs(i)
if graph_cyclic():
cc_cyclic += 1
print(cc_cyclic)
``` | instruction | 0 | 10,540 | 13 | 21,080 |
No | output | 1 | 10,540 | 13 | 21,081 |
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 graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example.
Submitted Solution:
```
class N:
def __init__(self, i) -> None:
self.i = i
self.st = None
self.ft = None
self.p = None
self.c = []
if __name__ == '__main__':
n, m = map(int, input().split())
arr = [N(i + 1) for i in range(n)]
for _ in range(m):
u, v = map(int, input().split())
u -= 1
v -= 1
arr[u].c.append(arr[v])
arr[v].c.append(arr[u])
t = 0
cdct = {}
for r in arr:
if r.ft:
continue
st = [r]
while st:
t += 1
r = st.pop()
if r.st:
r.ft = t
continue
r.st = t
st.append(r)
for c in r.c:
if c == r.p:
continue
if not c.ft:
if c.st:
cy = (min(c.i, r.i), max(c.i, r.i))
if c.i in cdct or r.i in cdct:
if c.i in cdct:
(u, v), _ = cdct[c.i]
cdct[u] = (u, v), False
cdct[v] = (u, v), False
if r.i in cdct:
(u, v), _ = cdct[r.i]
cdct[u] = (u, v), False
cdct[v] = (u, v), False
cdct[c.i] = cy, False
cdct[r.i] = cy, False
else:
cdct[c.i] = cy, True
cdct[r.i] = cy, True
else:
t += 1
c.p = r
st.append(c)
print(len(set(cy for cy, tv in cdct.values() if tv)))
``` | instruction | 0 | 10,541 | 13 | 21,082 |
No | output | 1 | 10,541 | 13 | 21,083 |
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 graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example.
Submitted Solution:
```
from sys import stdin,stdout
class DFS_General:
def __init__(self, edges, n):
self.n = n
self.pi = [-1 for _ in range(n)]
self.visit = [False for _ in range(n)]
self.Ady = edges
self.compo = [-1 for _ in range(n)]
self.count = -1
def DFS_visit(self, u):
self.visit[u] = True
for v in self.Ady[u]:
if not self.visit[v]:
self.pi[v] = u
self.DFS_visit(v)
self.compo[u] = self.count
def DFS(self):
for i in range(self.n):
if not self.visit[i]:
self.count += 1
self.DFS_visit(i)
def Solution(Ady, n, degree):
DFS_ = DFS_General(Ady, n)
DFS_.DFS()
verif = [True for _ in range(DFS_.count)]
for i in range(n):
if degree[i] != 2:
verif [DFS_.compo[i]] = False
var = 0
for item in verif:
if item:
var += 1
return var
n_m = stdin.readline().split()
n = int(n_m[0])
m = int(n_m[1])
Ady = [[] for _ in range(n)]
degree = [0 for _ in range(n)]
for i in range(m):
stri= stdin.readline().split()
item = (int(stri[0])-1, int(stri[1])-1)
Ady[item[0]].append(item[1])
Ady[item[1]].append(item[0])
degree[item[0]]+=1
degree[item[1]]+=1
stdout.write('ccccccccc')
stdout.write(str(Solution(Ady,n,degree)))
``` | instruction | 0 | 10,542 | 13 | 21,084 |
No | output | 1 | 10,542 | 13 | 21,085 |
Provide a correct Python 3 solution for this coding contest problem.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First | instruction | 0 | 10,582 | 13 | 21,164 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(2 * 10 ** 5 + 5)
def dfs(v, p, links):
farthest_d = 0
farthest_v = v
for u in links[v]:
if u == p:
continue
res_d, res_v = dfs(u, v, links)
if res_d > farthest_d:
farthest_d = res_d
farthest_v = res_v
return farthest_d + 1, farthest_v
def solve(n, links):
if n == 1:
return True
d, v = dfs(0, -1, links)
d, v = dfs(v, -1, links)
if (d + 1) % 3 == 0:
return False
return True
n = int(input())
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('First' if solve(n, links) else 'Second')
``` | output | 1 | 10,582 | 13 | 21,165 |
Provide a correct Python 3 solution for this coding contest problem.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First | instruction | 0 | 10,583 | 13 | 21,166 |
"Correct Solution:
```
class Tree():
def __init__(self, n, decrement=1):
self.n = n
self.edges = [[] for _ in range(n)]
self.root = None
self.depth = [-1]*n
self.size = [1]*n # 部分木のノードの数
self.decrement = decrement
def add_edge(self, u, v):
u, v = u-self.decrement, v-self.decrement
self.edges[u].append(v)
self.edges[v].append(u)
def add_edges(self, edges):
for u, v in edges:
u, v = u-self.decrement, v-self.decrement
self.edges[u].append(v)
self.edges[v].append(u)
def set_root(self, root):
root -= self.decrement
self.root = root
self.par = [-1]*self.n
self.depth[root] = 0
self.order = [root] # 帰りがけに使う
next_set = [root]
while next_set:
p = next_set.pop()
for q in self.edges[p]:
if self.depth[q] != -1: continue
self.par[q] = p
self.depth[q] = self.depth[p]+1
self.order.append(q)
next_set.append(q)
for p in self.order[::-1]:
for q in self.edges[p]:
if self.par[p] == q: continue
self.size[p] += self.size[q]
def diameter(self, path=False):
# assert self.root is not None
u = self.depth.index(max(self.depth))
dist = [-1]*self.n
dist[u] = 0
prev = [-1]*self.n
next_set = [u]
while next_set:
p = next_set.pop()
for q in self.edges[p]:
if dist[q] != -1: continue
dist[q] = dist[p]+1
prev[q] = p
next_set.append(q)
d = max(dist)
if path:
v = w = dist.index(d)
path = [v+1]
while w != u:
w = prev[w]
path.append(w+self.decrement)
return d, v+self.decrement, u+self.decrement, path
else: return d
def heavy_light_decomposition(self):
"""
heavy edge を並べてリストにした物を返す (1-indexed if decrement=True)
"""
# assert self.root is not None
self.vid = [-1]*self.n
self.hld = [-1]*self.n
self.head = [-1]*self.n
self.head[self.root] = self.root
self.heavy_node = [-1]*self.n
next_set = [self.root]
for i in range(self.n):
""" for tree graph, dfs ends in N times """
p = next_set.pop()
self.vid[p] = i
self.hld[i] = p+self.decrement
maxs = 0
for q in self.edges[p]:
""" encode direction of Heavy edge into heavy_node """
if self.par[p] == q: continue
if maxs < self.size[q]:
maxs = self.size[q]
self.heavy_node[p] = q
for q in self.edges[p]:
""" determine "head" of heavy edge """
if self.par[p] == q or self.heavy_node[p] == q: continue
self.head[q] = q
next_set.append(q)
if self.heavy_node[p] != -1:
self.head[self.heavy_node[p]] = self.head[p]
next_set.append(self.heavy_node[p])
return self.hld
def lca(self, u, v):
# assert self.head is not None
u, v = u-self.decrement, v-self.decrement
while True:
if self.vid[u] > self.vid[v]: u, v = v, u
if self.head[u] != self.head[v]:
v = self.par[self.head[v]]
else:
return u + self.decrement
def path(self, u, v):
""" u-v 間の最短経路をリストで返す """
p = self.lca(u, v)
u, v, p = u-self.decrement, v-self.decrement, p-self.decrement
R = []
while u != p:
yield u+self.decrement
u = self.par[u]
yield p+self.decrement
while v != p:
R.append(v)
v = self.par[v]
for v in reversed(R):
yield v+self.decrement
def distance(self, u, v):
# assert self.head is not None
p = self.lca(u, v)
u, v, p = u-self.decrement, v-self.decrement, p-self.decrement
return self.depth[u] + self.depth[v] - 2*self.depth[p]
def find(self, u, v, x):
return self.distance(u,x)+self.distance(x,v)==self.distance(u,v)
def path_to_list(self, u, v, edge_query=False):
"""
パス上の頂点の集合を self.hld 上の開区間の集合として表す
ここで、self.hld は heavy edge を並べて数列にしたものである
"""
# assert self.head is not None
u, v = u-self.decrement, v-self.decrement
while True:
if self.vid[u] > self.vid[v]: u, v = v, u
if self.head[u] != self.head[v]:
yield self.vid[self.head[v]], self.vid[v] + 1
v = self.par[self.head[v]]
else:
yield self.vid[u] + edge_query, self.vid[v] + 1
return
def point(self, u):
return self.vid[u-self.decrement]
def subtree_query(self, u):
u -= self.decrement
return self.vid[u], self.vid[u] + self.size[u]
def draw(self):
import matplotlib.pyplot as plt
import networkx as nx
G = nx.Graph()
for x in range(self.n):
for y in self.edges[x]:
G.add_edge(x + self.decrement, y + self.decrement)
pos = nx.spring_layout(G)
nx.draw_networkx(G, pos)
plt.axis("off")
plt.show()
##################################################################################################
import sys
input = sys.stdin.readline
N = int(input())
T = Tree(N)
for _ in range(N-1):
x, y = map(int, input().split())
T.add_edge(x, y)
T.set_root(1)
print("Second" if (T.diameter()+1)%3==2 else "First")
``` | output | 1 | 10,583 | 13 | 21,167 |
Provide a correct Python 3 solution for this coding contest problem.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First | instruction | 0 | 10,584 | 13 | 21,168 |
"Correct Solution:
```
def getD(graph):
# search edge
origin=1
d = 0
queue = Queue()
for it in graph[origin]:
queue.enqueue((it, origin, d+1)) # next, coming from, depth
while queue.size() > 0:
leaf, origin, d = queue.dequeue()
for it in graph[leaf]:
if it != origin:
queue.enqueue((it, leaf, d+1)) # next, coming from, depth
# print(d, leaf)
# search D
origin=leaf
d = 0
queue = Queue()
for it in graph[origin]:
queue.enqueue((it, origin, d+1)) # next, coming from, depth
while queue.size() > 0:
leaf, origin, d = queue.dequeue()
for it in graph[leaf]:
if it != origin:
queue.enqueue((it, leaf, d+1)) # next, coming from, depth
# print(d, leaf)
return d
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.head = None
self.last = None
self._size = 0
def enqueue(self, data):
if self.last is None:
self.head = Node(data)
self.last = self.head
else:
self.last.next = Node(data)
self.last = self.last.next
self._size += 1
def dequeue(self):
if self.head is None:
return None
else:
to_return = self.head.data
self.head = self.head.next
self._size -= 1
if self._size == 0:
self.head = None
self.last = None
return to_return
def size(self):
return self._size
def inside(y,x,H,W):
if 0<=y<H and 0<=x<W:
return True
else:
return False
def addQueueIfPossible(new_y, new_x, new_val, data, queue):
if inside(new_y, new_x, H, W) and data[new_y][new_x]==-1:
data[new_y][new_x] = new_val
queue.enqueue((new_y, new_x, new_val))
return True
else:
return False
n = int(input())
graph = [[] for _ in range(n+1)]
for i in range(n-1):
a,b = map(int, input().split())
graph[a].append(b)
graph[b].append(a)
if n==1:
print('First')
else:
d = getD(graph)
if (d+2)%3==0:
print('Second')
else:
print('First')
``` | output | 1 | 10,584 | 13 | 21,169 |
Provide a correct Python 3 solution for this coding contest problem.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First | instruction | 0 | 10,585 | 13 | 21,170 |
"Correct Solution:
```
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(300000)
def dfs(idx, con, visited):
visited[idx] = True
max_depth = 0
max_len = 0
depths = []
if idx >= len(con):
return max_depth, max_len
for v in con[idx]:
if v < len(visited) and not visited[v]:
max_d, max_l = dfs(v, con, visited)
max_len = max(max_len, max_l)
depths.append(max_d + 1)
if len(depths) > 0:
depths.sort(reverse=True)
max_depth = depths[0]
if len(depths) > 1:
max_len = max(max_len, depths[0] + depths[1])
else:
max_len = max(max_len, depths[0])
visited[idx] = False
return max_depth, max_len
def solve(N: int, A: "List[int]", B: "List[int]"):
con = [[] for _ in range(N)]
for i in range(len(A)):
a = A[i] - 1
b = B[i] - 1
con[a].append(b)
con[b].append(a)
#print(con)
visited = [False] * N
max_depth, max_len = dfs(0, con, visited)
#print(max_len)
if (max_len + 1) % 3 == 2:
ret = 'Second'
else:
ret = 'First'
print(ret)
return
def main():
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
N = int(next(tokens)) # type: int
a = [int()] * (N-1) # type: "List[int]"
b = [int()] * (N-1) # type: "List[int]"
for i in range(N-1):
a[i] = int(next(tokens))
b[i] = int(next(tokens))
solve(N, a, b)
if __name__ == '__main__':
main()
``` | output | 1 | 10,585 | 13 | 21,171 |
Provide a correct Python 3 solution for this coding contest problem.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First | instruction | 0 | 10,586 | 13 | 21,172 |
"Correct Solution:
```
from collections import defaultdict
N = int(input())
abList = [list(map(int, input().split())) for _ in range(N-1)]
# 木構造の関係リスト作成
treeDict = defaultdict(list)
for a, b in abList:
treeDict[a].append(b)
treeDict[b].append(a)
# コストの辞書と疑似キューを作成
costDict = defaultdict(int)
treeQ = set()
# 葉(端)のコストを1にし、隣接ノードをキューに格納
for node in treeDict:
if len(treeDict[node]) == 1:
costDict[node] = 1
treeQ.add(treeDict[node][0])
# 1つを除く隣接ノードにコストが設定されている(!= 0)場合、
# 隣接ノードの最大コスト + 1 でコストを設定し、コスト未設定のノードをキューに格納。
# 上記をキューに値が入らなくなるまで繰り返す。
node = 1
while(treeQ):
tQ = set()
costList = []
for node in treeQ:
if costDict[node] != 0: break
decidedFlg = True
cost = -1
qNode = -1
for nextNode in treeDict[node]:
nextCost = costDict[nextNode]
if nextCost == 0:
# 隣接ノードがコスト未設定ならキューに格納
# 隣接ノードが2つコスト未設定ならbreak
if not decidedFlg:
cost = -1
qNode = -1
break
decidedFlg = False
qNode = nextNode
else:
# コストが設定されていれば大きいコストで更新
cost = max(cost, nextCost + 1)
if cost != -1:
costList.append((node, cost))
if qNode != -1:
tQ.add(qNode)
for cost in costList:
costDict[cost[0]] = cost[1]
treeQ = tQ
# コストが設定されていないノードを頂点として直径を図る
firstLen, secondLen = 0, 0
for nextNode in treeDict[node]:
cost = costDict[nextNode]
if cost > firstLen:
secondLen = firstLen
firstLen = cost
elif cost > secondLen:
secondLen = cost
diameter = firstLen + secondLen + 1
ans = "First" if diameter % 3 != 2 else "Second"
print(ans)
``` | output | 1 | 10,586 | 13 | 21,173 |
Provide a correct Python 3 solution for this coding contest problem.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First | instruction | 0 | 10,587 | 13 | 21,174 |
"Correct Solution:
```
n,*L=map(int,open(0).read().split())
con=[[]for _ in range(n)]
for a,b in zip(*[iter(L)]*2):
con[a-1].append(b-1)
con[b-1].append(a-1)
dist=[-1]*n
dist[0]=0
farthest=0
q=[0]
while q:
cur=q.pop()
for nxt in con[cur]:
if dist[nxt]<0:
dist[nxt]=dist[cur]+1
if dist[farthest]<dist[nxt]:
farthest=nxt
q.append(nxt)
dist=[-1]*n
dist[farthest]=0
diameter=0
q=[farthest]
while q:
cur=q.pop()
for nxt in con[cur]:
if dist[nxt]<0:
dist[nxt]=dist[cur]+1
diameter=max(diameter,dist[nxt])
q.append(nxt)
print("Second" if diameter%3==1 else "First")
``` | output | 1 | 10,587 | 13 | 21,175 |
Provide a correct Python 3 solution for this coding contest problem.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First | instruction | 0 | 10,588 | 13 | 21,176 |
"Correct Solution:
```
#!/usr/bin/env python3
import sys
import heapq
INF = float("inf")
def argmax(a):
m, n = -(1 << 31), -1
for i, v in enumerate(a):
if m < v:
m, n = v, i
return m, n
# 無向グラフを仮定する。
class Graph(object):
def __init__(self, N):
self.N = N
self.V = list(range(N))
self.E = [[] for _ in range(N)]
def add_edge(self, edge):
"""辺を加える。edgeは(始点, 終点、重み)からなるリスト
重みがなければ、重み1とする。
"""
if len(edge) == 2:
edge.append(1)
elif len(edge) != 3:
print("error in add_edge")
pass
s, t, w = edge
self.E[s].append([t, w])
self.E[t].append([s, w]) # 無向グラフを仮定。逆向きにも辺を張る
pass
def shortestPath(g: Graph, s: int):
""" グラフgにおいて、始点sから各頂点への最短路を求める
引数
g: グラフ, s: 始点
返り値
dist: 始点からの距離が格納されたリスト
prev: 始点から最短経路で移動する場合、各頂点に至る前の頂点のリスト
"""
dist = [INF]*g.N
dist[s] = 0
prev = [None]*g.N
Q = []
heapq.heappush(Q, (dist[s], s))
while len(Q) > 0:
_, u = heapq.heappop(Q)
for v, w in g.E[u]:
if dist[v] > dist[u] + w:
dist[v] = dist[u] + w
prev[v] = u
heapq.heappush(Q, (dist[v], v))
return dist, prev
def tree_diameter(g):
# 木の直径を求める。
# ダイクストラ法を二回行う実装。
dist, prev = shortestPath(g, 0)
m, s = argmax(dist)
dist, prev = shortestPath(g, s)
return max(dist)
def solve(N: int, a: "List[int]", b: "List[int]"):
g = Graph(N)
for aa, bb in zip(a, b):
g.add_edge([aa-1, bb-1])
L = tree_diameter(g)
if L % 3 == 1:
print("Second")
else:
print("First")
return
def main():
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
N = int(next(tokens)) # type: int
a = [int()] * (N-1) # type: "List[int]"
b = [int()] * (N-1) # type: "List[int]"
for i in range(N-1):
a[i] = int(next(tokens))
b[i] = int(next(tokens))
solve(N, a, b)
if __name__ == '__main__':
main()
``` | output | 1 | 10,588 | 13 | 21,177 |
Provide a correct Python 3 solution for this coding contest problem.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First | instruction | 0 | 10,589 | 13 | 21,178 |
"Correct Solution:
```
from collections import defaultdict
import sys
input = sys.stdin.readline
N = int(input())
# 例外処理
if (N == 1):
print("First")
quit()
tree = defaultdict(set)
tree_main = defaultdict(set)
for i in range(N-1):
a, b = tuple(map(int, input().split()))
tree[a].add(b)
tree[b].add(a)
tree_main[a].add(b)
tree_main[b].add(a)
def longest_path(tree, from_node=1):
cnt = 1
nearest_nodes = list(tree[from_node])
while len(nearest_nodes) > 0:
for one_step_node in nearest_nodes:
for two_step_node in tree[one_step_node]:
if two_step_node != from_node:
tree[two_step_node].remove(one_step_node)
tree[two_step_node].add(from_node)
tree[from_node].add(two_step_node)
tree[from_node].remove(one_step_node)
cnt += 1
nearest_nodes = list(tree[from_node])
return one_step_node, cnt
far, _ = longest_path(tree)
_, n = longest_path(tree_main, far)
print("Second" if n % 3 == 2 else "First")
``` | output | 1 | 10,589 | 13 | 21,179 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First
Submitted Solution:
```
n = int(input())
g = [[] for _ in range(n)]
for i in range(n - 1):
a, b = map(int, input().split())
g[a - 1].append(b - 1)
g[b - 1].append(a - 1)
s = [0]
d = [-1] * n
d[0] = 0
while s:
p = s.pop()
for node in g[p]:
if d[node] == -1:
s.append(node)
d[node] = d[p] + 1
idx = 0
for i in range(n):
if d[i] > d[idx]:
idx = i
s = [idx]
d = [-1] * n
d[idx] = 0
while s:
p = s.pop()
for node in g[p]:
if d[node] == -1:
s.append(node)
d[node] = d[p] + 1
m = 0
for i in range(n):
if d[i] > m:
m = d[i]
if m % 3 == 1:
print('Second')
else:
print('First')
``` | instruction | 0 | 10,590 | 13 | 21,180 |
Yes | output | 1 | 10,590 | 13 | 21,181 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First
Submitted Solution:
```
n = int(input())
link = [[] for _ in range(n)]
for i in range(n-1):
a,b = list(map(int,input().split()))
link[a-1].append(b-1)
link[b-1].append(a-1)
from collections import deque
Q = deque()
Q.append([0,0])
visited=[-1]*n
visited[0]=0
mx_dist=0
mx_ind=0
while Q:
now,cnt = Q.popleft()
for nxt in link[now]:
if visited[nxt]!=-1:
continue
visited[nxt]=cnt+1
Q.append([nxt,cnt+1])
if mx_dist < cnt+1:
mx_dist=cnt+1
mx_ind = nxt
Q = deque()
Q.append([mx_ind,0])
visited=[-1]*n
visited[mx_ind]=0
mx_dist=0
while Q:
now,cnt = Q.popleft()
for nxt in link[now]:
if visited[nxt]!=-1:
continue
visited[nxt]=cnt+1
Q.append([nxt,cnt+1])
if mx_dist < cnt+1:
mx_dist=cnt+1
mx_ind = nxt
if (mx_dist-1)%3==0:
print("Second")
else:
print("First")
``` | instruction | 0 | 10,591 | 13 | 21,182 |
Yes | output | 1 | 10,591 | 13 | 21,183 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First
Submitted Solution:
```
from collections import defaultdict as dd
N = int(input())
Es = dd(dict)
for _ in range(N-1):
a, b = map(int, input().split())
Es[a-1][b-1] = Es[b-1][a-1] = 1
# もっとも長いパスを見つける
q = [0]
visited = [False] * N
last = None
while q:
nq = []
for node in q:
last = node
visited[node] = True
for to in Es[node]:
if visited[to]:
continue
nq.append(to)
q = nq
q = [last]
visited = [False] * N
n = 0
while q:
n += 1
nq = []
for node in q:
visited[node] = True
for to in Es[node]:
if visited[to]:
continue
nq.append(to)
q = nq
if n % 3 == 2:
print('Second')
else:
print('First')
``` | instruction | 0 | 10,592 | 13 | 21,184 |
Yes | output | 1 | 10,592 | 13 | 21,185 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First
Submitted Solution:
```
N=int(input())
if N==1:
print("First")
exit()
L=[[]for i in range(N+1)]
for i in range(N-1):
a,b=map(int,input().split())
L[a].append(b)
L[b].append(a)
#print(L)
C=[0 for i in range(N+1)]
D=[10000000 for i in range(N+1)]
D[1]=0
Q=[1]
for i in range(10**6):
if i==N:
break
for j in L[Q[i]]:
if D[j]==10000000:
Q.append(j)
D[j]=D[Q[i]]+1
#print(D)
F=0
cnt=0
for i in range(1,N+1):
if D[i]>cnt:
cnt=D[i]
F=i
d=[10000000 for i in range(N+1)]
d[F]=0
Q=[F]
for i in range(10**6):
if i==N:
break
for j in L[Q[i]]:
if d[j]==10000000:
Q.append(j)
d[j]=d[Q[i]]+1
#print(d)
ans=0
for i in range(1,N+1):
if d[i]>ans:
ans=d[i]
if ans%3==1:
print("Second")
else:
print("First")
``` | instruction | 0 | 10,593 | 13 | 21,186 |
Yes | output | 1 | 10,593 | 13 | 21,187 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First
Submitted Solution:
```
N = int(input())
src = [tuple(map(lambda x:int(x)-1,input().split())) for i in range(N-1)]
es = [[] for i in range(N)]
for a,b in src:
es[a].append(b)
es[b].append(a)
if all(len(e)<=2 for e in es):
print('First' if N%2 else 'Second')
exit()
assert False
``` | instruction | 0 | 10,594 | 13 | 21,188 |
No | output | 1 | 10,594 | 13 | 21,189 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First
Submitted Solution:
```
print(["Second","First"][int(input())%2])
``` | instruction | 0 | 10,595 | 13 | 21,190 |
No | output | 1 | 10,595 | 13 | 21,191 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First
Submitted Solution:
```
N = int(input())
S = list(input())
ans = N % 2
if ans == 0:
print("Secound")
else:
print("First")
``` | instruction | 0 | 10,596 | 13 | 21,192 |
No | output | 1 | 10,596 | 13 | 21,193 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First
Submitted Solution:
```
def s(x,v,d):
r=[d,v]
for u in g[v]:
if u!=x:
t=s(v,u,d+1)
if r[0]<t[0]:r=t
return r
n,*t=map(int,open(0).read().split())
g=[set()for _ in range(n+1)]
for a,b in zip(t[::2],t[1::2]):
g[a].add(b)
g[b].add(a)
print('SFeicrosntd'[s(0,s(0,1,0)[1],0)[0]%3!=1::2])
``` | instruction | 0 | 10,597 | 13 | 21,194 |
No | output | 1 | 10,597 | 13 | 21,195 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Consider an infinite N-ary tree as shown below:
<image>
Figure: an infinite N-ary tree for the case N = 3
As shown in the figure, each vertex is indexed with a unique positive integer, and for every positive integer there is a vertex indexed with it. The root of the tree has the index 1. For the remaining vertices, vertices in the upper row have smaller indices than those in the lower row. Among the vertices in the same row, a vertex that is more to the left has a smaller index.
Regarding this tree, process Q queries. The i-th query is as follows:
* Find the index of the lowest common ancestor (see Notes) of Vertex v_i and w_i.
Constraints
* 1 ≤ N ≤ 10^9
* 1 ≤ Q ≤ 10^5
* 1 ≤ v_i < w_i ≤ 10^9
Input
Input is given from Standard Input in the following format:
N Q
v_1 w_1
:
v_Q w_Q
Output
Print Q lines. The i-th line (1 ≤ i ≤ Q) must contain the index of the lowest common ancestor of Vertex v_i and w_i.
Examples
Input
3 3
5 7
8 11
3 9
Output
2
1
3
Input
100000 2
1 2
3 4
Output
1
1 | instruction | 0 | 10,624 | 13 | 21,248 |
"Correct Solution:
```
def main():
n,q,*t=map(int,open(0).read().split())
for v,w in zip(t[::2],t[1::2]):
if n<2:
print(min(v,w))
continue
s,t=[],[]
while v:
s.append(v)
v=(v+n-2)//n
while w:
t.append(w)
w=(w+n-2)//n
print(max(set(s)&set(t)))
if __name__=='__main__':
main()
``` | output | 1 | 10,624 | 13 | 21,249 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Consider an infinite N-ary tree as shown below:
<image>
Figure: an infinite N-ary tree for the case N = 3
As shown in the figure, each vertex is indexed with a unique positive integer, and for every positive integer there is a vertex indexed with it. The root of the tree has the index 1. For the remaining vertices, vertices in the upper row have smaller indices than those in the lower row. Among the vertices in the same row, a vertex that is more to the left has a smaller index.
Regarding this tree, process Q queries. The i-th query is as follows:
* Find the index of the lowest common ancestor (see Notes) of Vertex v_i and w_i.
Constraints
* 1 ≤ N ≤ 10^9
* 1 ≤ Q ≤ 10^5
* 1 ≤ v_i < w_i ≤ 10^9
Input
Input is given from Standard Input in the following format:
N Q
v_1 w_1
:
v_Q w_Q
Output
Print Q lines. The i-th line (1 ≤ i ≤ Q) must contain the index of the lowest common ancestor of Vertex v_i and w_i.
Examples
Input
3 3
5 7
8 11
3 9
Output
2
1
3
Input
100000 2
1 2
3 4
Output
1
1 | instruction | 0 | 10,625 | 13 | 21,250 |
"Correct Solution:
```
N,Q = map(int,input().split())
if N == 1:
for i in range(Q):
print(min(map(int,input().split())))
exit()
def solve(s):
a,b = map(int,s.split())
while a != b:
if a < b: a,b = b,a
a = (a+N-2) // N
return str(a)
print('\n'.join(map(solve, [input() for i in range(Q)])))
``` | output | 1 | 10,625 | 13 | 21,251 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Consider an infinite N-ary tree as shown below:
<image>
Figure: an infinite N-ary tree for the case N = 3
As shown in the figure, each vertex is indexed with a unique positive integer, and for every positive integer there is a vertex indexed with it. The root of the tree has the index 1. For the remaining vertices, vertices in the upper row have smaller indices than those in the lower row. Among the vertices in the same row, a vertex that is more to the left has a smaller index.
Regarding this tree, process Q queries. The i-th query is as follows:
* Find the index of the lowest common ancestor (see Notes) of Vertex v_i and w_i.
Constraints
* 1 ≤ N ≤ 10^9
* 1 ≤ Q ≤ 10^5
* 1 ≤ v_i < w_i ≤ 10^9
Input
Input is given from Standard Input in the following format:
N Q
v_1 w_1
:
v_Q w_Q
Output
Print Q lines. The i-th line (1 ≤ i ≤ Q) must contain the index of the lowest common ancestor of Vertex v_i and w_i.
Examples
Input
3 3
5 7
8 11
3 9
Output
2
1
3
Input
100000 2
1 2
3 4
Output
1
1 | instruction | 0 | 10,626 | 13 | 21,252 |
"Correct Solution:
```
import sys
input=sys.stdin.readline
n,q=map(int,input().split())
for i in range(q):
u,v=map(int,input().split())
if n==1:
print(min(u,v))
continue
u-=1
v-=1
while u!=v:
if u>v:
if (u-1)//n>v:
u=(((u-1)//n)-1)//n
else:
u=(u-1)//n
else:
if (v-1)//n>v:
v=(((v-1)//n)-1)//n
else:
v=(v-1)//n
print(u+1)
``` | output | 1 | 10,626 | 13 | 21,253 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Consider an infinite N-ary tree as shown below:
<image>
Figure: an infinite N-ary tree for the case N = 3
As shown in the figure, each vertex is indexed with a unique positive integer, and for every positive integer there is a vertex indexed with it. The root of the tree has the index 1. For the remaining vertices, vertices in the upper row have smaller indices than those in the lower row. Among the vertices in the same row, a vertex that is more to the left has a smaller index.
Regarding this tree, process Q queries. The i-th query is as follows:
* Find the index of the lowest common ancestor (see Notes) of Vertex v_i and w_i.
Constraints
* 1 ≤ N ≤ 10^9
* 1 ≤ Q ≤ 10^5
* 1 ≤ v_i < w_i ≤ 10^9
Input
Input is given from Standard Input in the following format:
N Q
v_1 w_1
:
v_Q w_Q
Output
Print Q lines. The i-th line (1 ≤ i ≤ Q) must contain the index of the lowest common ancestor of Vertex v_i and w_i.
Examples
Input
3 3
5 7
8 11
3 9
Output
2
1
3
Input
100000 2
1 2
3 4
Output
1
1 | instruction | 0 | 10,627 | 13 | 21,254 |
"Correct Solution:
```
N, Q = map(int, input().split())
if N == 1:
for i in range(Q):
V, W = map(int, input().split())
print(min(V, W))
else:
p = []
p.append(1)
for i in range(40):
p.append(p[-1] * N)
for i in range(Q):
V, W = map(int, input().split())
v = []
w = []
dv = 0
dw = 0
while V > (p[dv + 1] - 1) // (N - 1): dv = dv + 1
while W > (p[dw + 1] - 1) // (N - 1): dw = dw + 1
v.append(V)
e = V
for j in range(dv, 0, -1):
e = (e - (p[j] - 1) // (N - 1) - 1) // N + (p[j - 1] - 1) // (N - 1) + 1;
v.append(e)
v.reverse()
w.append(W)
e = W
for j in range(dw, 0, -1):
e = (e - (p[j] - 1) // (N - 1) - 1) // N + (p[j - 1] - 1) // (N - 1) + 1;
w.append(e)
w.reverse()
ans = 1
j = 0
while j < len(v) and j < len(w) and v[j] == w[j]:
ans = v[j]
j = j + 1
print(ans)
``` | output | 1 | 10,627 | 13 | 21,255 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Consider an infinite N-ary tree as shown below:
<image>
Figure: an infinite N-ary tree for the case N = 3
As shown in the figure, each vertex is indexed with a unique positive integer, and for every positive integer there is a vertex indexed with it. The root of the tree has the index 1. For the remaining vertices, vertices in the upper row have smaller indices than those in the lower row. Among the vertices in the same row, a vertex that is more to the left has a smaller index.
Regarding this tree, process Q queries. The i-th query is as follows:
* Find the index of the lowest common ancestor (see Notes) of Vertex v_i and w_i.
Constraints
* 1 ≤ N ≤ 10^9
* 1 ≤ Q ≤ 10^5
* 1 ≤ v_i < w_i ≤ 10^9
Input
Input is given from Standard Input in the following format:
N Q
v_1 w_1
:
v_Q w_Q
Output
Print Q lines. The i-th line (1 ≤ i ≤ Q) must contain the index of the lowest common ancestor of Vertex v_i and w_i.
Examples
Input
3 3
5 7
8 11
3 9
Output
2
1
3
Input
100000 2
1 2
3 4
Output
1
1 | instruction | 0 | 10,628 | 13 | 21,256 |
"Correct Solution:
```
from bisect import *
from sys import stdin, stdout
readline = stdin.readline
N, Q = map(int, readline().split())
ans = []
if N == 1:
for q in range(Q):
v, w = map(int, readline().split())
ans.append(str(v))
else:
c = 1
B = [1]
while c < 10**9:
B.append(c+1)
c = c*N + 1
for q in range(Q):
v, w = map(int, readline().split())
lv = bisect(B, v)
lw = bisect(B, w)
if lv < lw:
w = (w + (B[lw-lv]-1)*(N-2)) // N**(lw-lv)
while v != w:
v = (v + (N - 2)) // N
w = (w + (N - 2)) // N
ans.append(str(v))
stdout.write("\n".join(ans))
stdout.write("\n")
``` | output | 1 | 10,628 | 13 | 21,257 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Consider an infinite N-ary tree as shown below:
<image>
Figure: an infinite N-ary tree for the case N = 3
As shown in the figure, each vertex is indexed with a unique positive integer, and for every positive integer there is a vertex indexed with it. The root of the tree has the index 1. For the remaining vertices, vertices in the upper row have smaller indices than those in the lower row. Among the vertices in the same row, a vertex that is more to the left has a smaller index.
Regarding this tree, process Q queries. The i-th query is as follows:
* Find the index of the lowest common ancestor (see Notes) of Vertex v_i and w_i.
Constraints
* 1 ≤ N ≤ 10^9
* 1 ≤ Q ≤ 10^5
* 1 ≤ v_i < w_i ≤ 10^9
Input
Input is given from Standard Input in the following format:
N Q
v_1 w_1
:
v_Q w_Q
Output
Print Q lines. The i-th line (1 ≤ i ≤ Q) must contain the index of the lowest common ancestor of Vertex v_i and w_i.
Examples
Input
3 3
5 7
8 11
3 9
Output
2
1
3
Input
100000 2
1 2
3 4
Output
1
1 | instruction | 0 | 10,629 | 13 | 21,258 |
"Correct Solution:
```
import sys
input = sys.stdin.readline
N,Q = map(int,input().split())
VW = [tuple(map(int,input().split())) for i in range(Q)]
ans = []
if N==1:
for v,w in VW:
ans.append(min(v,w))
else:
for v,w in VW:
while v != w:
if v > w: v,w = w,v
w = (w+N-2)//N
ans.append(v)
print(*ans, sep='\n')
``` | output | 1 | 10,629 | 13 | 21,259 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Consider an infinite N-ary tree as shown below:
<image>
Figure: an infinite N-ary tree for the case N = 3
As shown in the figure, each vertex is indexed with a unique positive integer, and for every positive integer there is a vertex indexed with it. The root of the tree has the index 1. For the remaining vertices, vertices in the upper row have smaller indices than those in the lower row. Among the vertices in the same row, a vertex that is more to the left has a smaller index.
Regarding this tree, process Q queries. The i-th query is as follows:
* Find the index of the lowest common ancestor (see Notes) of Vertex v_i and w_i.
Constraints
* 1 ≤ N ≤ 10^9
* 1 ≤ Q ≤ 10^5
* 1 ≤ v_i < w_i ≤ 10^9
Input
Input is given from Standard Input in the following format:
N Q
v_1 w_1
:
v_Q w_Q
Output
Print Q lines. The i-th line (1 ≤ i ≤ Q) must contain the index of the lowest common ancestor of Vertex v_i and w_i.
Examples
Input
3 3
5 7
8 11
3 9
Output
2
1
3
Input
100000 2
1 2
3 4
Output
1
1 | instruction | 0 | 10,630 | 13 | 21,260 |
"Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)
N, Q = map(int, input().split())
if N == 1:
ans = [min(map(int, input().split())) for _ in range(Q)]
print(*ans, sep="\n")
exit()
ans = [-1] * Q
for i in range(Q):
x, y = map(int, input().split())
x_memo = [x]
y_memo = [y]
while x:
x = (x + N - 2) // N
x_memo.append(x)
while y:
y = (y + N - 2) // N
y_memo.append(y)
res = -1
while x_memo and y_memo:
xi = x_memo.pop()
yi = y_memo.pop()
if xi == yi:
res = xi
else:
break
ans[i] = res
print(*ans, sep="\n")
``` | output | 1 | 10,630 | 13 | 21,261 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Consider an infinite N-ary tree as shown below:
<image>
Figure: an infinite N-ary tree for the case N = 3
As shown in the figure, each vertex is indexed with a unique positive integer, and for every positive integer there is a vertex indexed with it. The root of the tree has the index 1. For the remaining vertices, vertices in the upper row have smaller indices than those in the lower row. Among the vertices in the same row, a vertex that is more to the left has a smaller index.
Regarding this tree, process Q queries. The i-th query is as follows:
* Find the index of the lowest common ancestor (see Notes) of Vertex v_i and w_i.
Constraints
* 1 ≤ N ≤ 10^9
* 1 ≤ Q ≤ 10^5
* 1 ≤ v_i < w_i ≤ 10^9
Input
Input is given from Standard Input in the following format:
N Q
v_1 w_1
:
v_Q w_Q
Output
Print Q lines. The i-th line (1 ≤ i ≤ Q) must contain the index of the lowest common ancestor of Vertex v_i and w_i.
Examples
Input
3 3
5 7
8 11
3 9
Output
2
1
3
Input
100000 2
1 2
3 4
Output
1
1 | instruction | 0 | 10,631 | 13 | 21,262 |
"Correct Solution:
```
import math
N, Q = map(int, input().split())
queries = []
for i in range(Q):
v, w = map(int, input().split())
queries.append([v, w])
if N == 1:
for v, w in queries:
print(min(v, w))
else:
for v, w in queries:
if 1 in [v, w]:
print(1)
else:
# v < w にする
v, w = min(v,w), max(v, w)
v -= 2
w -= 2
v_parents = [v]
isReported = False
while v > 0:
v_parents.append(v // N - 1)
v = v//N-1
while w > 0:
w = w // N-1
if w in v_parents:
print(w+2)
isReported = True
break
if not isReported:
print(1)
``` | output | 1 | 10,631 | 13 | 21,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 integer N. Consider an infinite N-ary tree as shown below:
<image>
Figure: an infinite N-ary tree for the case N = 3
As shown in the figure, each vertex is indexed with a unique positive integer, and for every positive integer there is a vertex indexed with it. The root of the tree has the index 1. For the remaining vertices, vertices in the upper row have smaller indices than those in the lower row. Among the vertices in the same row, a vertex that is more to the left has a smaller index.
Regarding this tree, process Q queries. The i-th query is as follows:
* Find the index of the lowest common ancestor (see Notes) of Vertex v_i and w_i.
Constraints
* 1 ≤ N ≤ 10^9
* 1 ≤ Q ≤ 10^5
* 1 ≤ v_i < w_i ≤ 10^9
Input
Input is given from Standard Input in the following format:
N Q
v_1 w_1
:
v_Q w_Q
Output
Print Q lines. The i-th line (1 ≤ i ≤ Q) must contain the index of the lowest common ancestor of Vertex v_i and w_i.
Examples
Input
3 3
5 7
8 11
3 9
Output
2
1
3
Input
100000 2
1 2
3 4
Output
1
1
Submitted Solution:
```
def main():
n,m=map(int,input().split())
ab=[list(map(int,input().split())) for _ in [0]*m]
if n==1:
for a,b in ab:
print(min(a,b))
return
for a,b in ab:
while a!=b:
a,b=min(a,b),max(a,b)
b=(b+n-2)//n
print(a)
main()
``` | instruction | 0 | 10,632 | 13 | 21,264 |
Yes | output | 1 | 10,632 | 13 | 21,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 integer N. Consider an infinite N-ary tree as shown below:
<image>
Figure: an infinite N-ary tree for the case N = 3
As shown in the figure, each vertex is indexed with a unique positive integer, and for every positive integer there is a vertex indexed with it. The root of the tree has the index 1. For the remaining vertices, vertices in the upper row have smaller indices than those in the lower row. Among the vertices in the same row, a vertex that is more to the left has a smaller index.
Regarding this tree, process Q queries. The i-th query is as follows:
* Find the index of the lowest common ancestor (see Notes) of Vertex v_i and w_i.
Constraints
* 1 ≤ N ≤ 10^9
* 1 ≤ Q ≤ 10^5
* 1 ≤ v_i < w_i ≤ 10^9
Input
Input is given from Standard Input in the following format:
N Q
v_1 w_1
:
v_Q w_Q
Output
Print Q lines. The i-th line (1 ≤ i ≤ Q) must contain the index of the lowest common ancestor of Vertex v_i and w_i.
Examples
Input
3 3
5 7
8 11
3 9
Output
2
1
3
Input
100000 2
1 2
3 4
Output
1
1
Submitted Solution:
```
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
INF = float('inf')
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LIM(): return list(map(lambda x:int(x) - 1, sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def LIRM(n): return [LIM() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
mod = 1000000007
n, q = LI()
for i, j in LIR(q):
if n == 1:
print(min(i, j))
else:
while i != j:
if i < j:
i, j = j, i
i = (i - 2) // n + 1
print(i)
``` | instruction | 0 | 10,633 | 13 | 21,266 |
Yes | output | 1 | 10,633 | 13 | 21,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 integer N. Consider an infinite N-ary tree as shown below:
<image>
Figure: an infinite N-ary tree for the case N = 3
As shown in the figure, each vertex is indexed with a unique positive integer, and for every positive integer there is a vertex indexed with it. The root of the tree has the index 1. For the remaining vertices, vertices in the upper row have smaller indices than those in the lower row. Among the vertices in the same row, a vertex that is more to the left has a smaller index.
Regarding this tree, process Q queries. The i-th query is as follows:
* Find the index of the lowest common ancestor (see Notes) of Vertex v_i and w_i.
Constraints
* 1 ≤ N ≤ 10^9
* 1 ≤ Q ≤ 10^5
* 1 ≤ v_i < w_i ≤ 10^9
Input
Input is given from Standard Input in the following format:
N Q
v_1 w_1
:
v_Q w_Q
Output
Print Q lines. The i-th line (1 ≤ i ≤ Q) must contain the index of the lowest common ancestor of Vertex v_i and w_i.
Examples
Input
3 3
5 7
8 11
3 9
Output
2
1
3
Input
100000 2
1 2
3 4
Output
1
1
Submitted Solution:
```
def main():
n,m=map(int,input().split())
ab=[list(map(int,input().split())) for _ in [0]*m]
if n==1:
for a,b in ab:
print(min(a,b))
return
for a,b in ab:
while a!=b:
if a<b:
b=(b+n-2)//n
else:
a=(a+n-2)//n
print(a)
main()
``` | instruction | 0 | 10,634 | 13 | 21,268 |
Yes | output | 1 | 10,634 | 13 | 21,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 integer N. Consider an infinite N-ary tree as shown below:
<image>
Figure: an infinite N-ary tree for the case N = 3
As shown in the figure, each vertex is indexed with a unique positive integer, and for every positive integer there is a vertex indexed with it. The root of the tree has the index 1. For the remaining vertices, vertices in the upper row have smaller indices than those in the lower row. Among the vertices in the same row, a vertex that is more to the left has a smaller index.
Regarding this tree, process Q queries. The i-th query is as follows:
* Find the index of the lowest common ancestor (see Notes) of Vertex v_i and w_i.
Constraints
* 1 ≤ N ≤ 10^9
* 1 ≤ Q ≤ 10^5
* 1 ≤ v_i < w_i ≤ 10^9
Input
Input is given from Standard Input in the following format:
N Q
v_1 w_1
:
v_Q w_Q
Output
Print Q lines. The i-th line (1 ≤ i ≤ Q) must contain the index of the lowest common ancestor of Vertex v_i and w_i.
Examples
Input
3 3
5 7
8 11
3 9
Output
2
1
3
Input
100000 2
1 2
3 4
Output
1
1
Submitted Solution:
```
n,q = map(int, input().split())
if n == 1:
for _ in range(q):
print(min(map(int, input().split())))
else:
for _ in range(q):
v,w = map(int, input().split())
while v != w:
if v > w:
v,w = w,v
w = (w+n-2)//n
print(v)
``` | instruction | 0 | 10,635 | 13 | 21,270 |
Yes | output | 1 | 10,635 | 13 | 21,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 integer N. Consider an infinite N-ary tree as shown below:
<image>
Figure: an infinite N-ary tree for the case N = 3
As shown in the figure, each vertex is indexed with a unique positive integer, and for every positive integer there is a vertex indexed with it. The root of the tree has the index 1. For the remaining vertices, vertices in the upper row have smaller indices than those in the lower row. Among the vertices in the same row, a vertex that is more to the left has a smaller index.
Regarding this tree, process Q queries. The i-th query is as follows:
* Find the index of the lowest common ancestor (see Notes) of Vertex v_i and w_i.
Constraints
* 1 ≤ N ≤ 10^9
* 1 ≤ Q ≤ 10^5
* 1 ≤ v_i < w_i ≤ 10^9
Input
Input is given from Standard Input in the following format:
N Q
v_1 w_1
:
v_Q w_Q
Output
Print Q lines. The i-th line (1 ≤ i ≤ Q) must contain the index of the lowest common ancestor of Vertex v_i and w_i.
Examples
Input
3 3
5 7
8 11
3 9
Output
2
1
3
Input
100000 2
1 2
3 4
Output
1
1
Submitted Solution:
```
def pre(x):
return (x + 1) // 3
N, Q = map(int, input().split())
for i in range(Q):
v, w = map(int, input().split())
while v != w:
if v < w:
w = pre(w)
else:
v = pre(v)
print(v)
``` | instruction | 0 | 10,636 | 13 | 21,272 |
No | output | 1 | 10,636 | 13 | 21,273 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer N. Consider an infinite N-ary tree as shown below:
<image>
Figure: an infinite N-ary tree for the case N = 3
As shown in the figure, each vertex is indexed with a unique positive integer, and for every positive integer there is a vertex indexed with it. The root of the tree has the index 1. For the remaining vertices, vertices in the upper row have smaller indices than those in the lower row. Among the vertices in the same row, a vertex that is more to the left has a smaller index.
Regarding this tree, process Q queries. The i-th query is as follows:
* Find the index of the lowest common ancestor (see Notes) of Vertex v_i and w_i.
Constraints
* 1 ≤ N ≤ 10^9
* 1 ≤ Q ≤ 10^5
* 1 ≤ v_i < w_i ≤ 10^9
Input
Input is given from Standard Input in the following format:
N Q
v_1 w_1
:
v_Q w_Q
Output
Print Q lines. The i-th line (1 ≤ i ≤ Q) must contain the index of the lowest common ancestor of Vertex v_i and w_i.
Examples
Input
3 3
5 7
8 11
3 9
Output
2
1
3
Input
100000 2
1 2
3 4
Output
1
1
Submitted Solution:
```
# -*- coding: utf-8 -*-
import math
def get_parent(child,n):
parent = 0
if(child%n <= 1):
parent = (child)//n
else:
parent = child//n + 1
return parent
n, q = list(map(int,input().split()))
if(n == 1):
for i in range(q):
v, w = list(map(int,input().split()))
print(min(v,w))
else:
right = [0 for i in range(int(math.log(10**9,n)+2))]
for i in range(len(right)):
right[i] = (n**(i+1)-1)//(n-1)
#print(right)
for i in range(q):
v, w = list(map(int,input().split()))
hv, hw = -1, -1
vparent, wparent = v, w
for j,r in enumerate(right):
if(hv == -1 and v<=r):hv = j
if(hw == -1 and w<=r):hw = j
for j in range(abs(hw-hv)):
if(hw>hv):
wparent = get_parent(wparent,n)
elif(hv>hw):
vparent = get_parent(vparent,n)
while(wparent!=vparent):
wparent = get_parent(wparent,n)
vparent = get_parent(vparent,n)
print(wparent)
``` | instruction | 0 | 10,637 | 13 | 21,274 |
No | output | 1 | 10,637 | 13 | 21,275 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer N. Consider an infinite N-ary tree as shown below:
<image>
Figure: an infinite N-ary tree for the case N = 3
As shown in the figure, each vertex is indexed with a unique positive integer, and for every positive integer there is a vertex indexed with it. The root of the tree has the index 1. For the remaining vertices, vertices in the upper row have smaller indices than those in the lower row. Among the vertices in the same row, a vertex that is more to the left has a smaller index.
Regarding this tree, process Q queries. The i-th query is as follows:
* Find the index of the lowest common ancestor (see Notes) of Vertex v_i and w_i.
Constraints
* 1 ≤ N ≤ 10^9
* 1 ≤ Q ≤ 10^5
* 1 ≤ v_i < w_i ≤ 10^9
Input
Input is given from Standard Input in the following format:
N Q
v_1 w_1
:
v_Q w_Q
Output
Print Q lines. The i-th line (1 ≤ i ≤ Q) must contain the index of the lowest common ancestor of Vertex v_i and w_i.
Examples
Input
3 3
5 7
8 11
3 9
Output
2
1
3
Input
100000 2
1 2
3 4
Output
1
1
Submitted Solution:
```
n,q=map(int,input().split())
for _ in range(q):
v,w=map(int,input().split())
while(v is not w):
if v < w:
w = (w+1)//3
else:
v = (v+1)//3
print(v)
``` | instruction | 0 | 10,638 | 13 | 21,276 |
No | output | 1 | 10,638 | 13 | 21,277 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer N. Consider an infinite N-ary tree as shown below:
<image>
Figure: an infinite N-ary tree for the case N = 3
As shown in the figure, each vertex is indexed with a unique positive integer, and for every positive integer there is a vertex indexed with it. The root of the tree has the index 1. For the remaining vertices, vertices in the upper row have smaller indices than those in the lower row. Among the vertices in the same row, a vertex that is more to the left has a smaller index.
Regarding this tree, process Q queries. The i-th query is as follows:
* Find the index of the lowest common ancestor (see Notes) of Vertex v_i and w_i.
Constraints
* 1 ≤ N ≤ 10^9
* 1 ≤ Q ≤ 10^5
* 1 ≤ v_i < w_i ≤ 10^9
Input
Input is given from Standard Input in the following format:
N Q
v_1 w_1
:
v_Q w_Q
Output
Print Q lines. The i-th line (1 ≤ i ≤ Q) must contain the index of the lowest common ancestor of Vertex v_i and w_i.
Examples
Input
3 3
5 7
8 11
3 9
Output
2
1
3
Input
100000 2
1 2
3 4
Output
1
1
Submitted Solution:
```
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
N,Q = map(int,input().split())
VW = [[int(x) for x in input().split()] for _ in range(Q)]
if N == 1:
answer = [min(v,w) for v,w in VW]
else:
answer = []
for v,w in VW:
while v != w:
if v > w:
v,w = w,v
w = (w+N-2)//N
answer.append(v)
print('\n'.join(map(str,answer)))
``` | instruction | 0 | 10,639 | 13 | 21,278 |
No | output | 1 | 10,639 | 13 | 21,279 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.