message stringlengths 2 49.9k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 446 108k | cluster float64 13 13 | __index_level_0__ int64 892 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types.
* `0 u v`: Add an edge (u, v).
* `1 u v`: Print 1 if u and v are in the same connected component, 0 otherwise.
Constraints
* 1 \leq N \leq 200,000
* 1 \leq Q \leq 200,000
* 0 \leq u_i, v_i \lt N
Input
Input is given from Standard Input in the following format:
N Q
t_1 u_1 v_1
t_2 u_2 v_2
:
t_Q u_Q v_Q
出力
For each query of the latter type, print the answer.
Example
Input
4 7
1 0 1
0 0 1
0 2 3
1 0 1
1 1 2
0 0 2
1 1 3
Output
0
1
0
1
Submitted Solution:
```
class UnionFind:
def __init__(self, length):
self.parent_indexes = [-1]* length
def union(self, i, j):
if i == j:
return
# iが所属する集団のサイズ>=jが所属する集団のサイズにする
if self.get_group_size(i) < self.get_group_size(j):
i, j = j, i
self.parent_indexes[i] = - self.get_group_size(i) - self.get_group_size(j)
self.parent_indexes[j] = self.find(i)
# i番目の要素が所属する集団の親nodeのindexを返す
# メモ化もする
def find(self, i):
if self.parent_indexes[i] < 0:
return i
parent_index = self.find(self.parent_indexes[i])
self.parent_indexes[i] = parent_index
return parent_index
def get_group_size(self, i):
return - self.parent_indexes[self.find(i)]
def are_in_the_same_group(self, i, j):
return self.find(i) == self.find(j)
n, q = list(map(lambda x: int(x), input().split()))
uf = UnionFind(n)
for _ in range(q):
t, u, v = list(map(lambda x: int(x), input().split()))
# print(uf.parent_indexes)
if t == 0:
uf.union(u, v)
continue
print('1') if uf.are_in_the_same_group(u, v) else print('0')
``` | instruction | 0 | 37,505 | 13 | 75,010 |
No | output | 1 | 37,505 | 13 | 75,011 |
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 with N vertices and 0 edges. Process Q queries of the following types.
* `0 u v`: Add an edge (u, v).
* `1 u v`: Print 1 if u and v are in the same connected component, 0 otherwise.
Constraints
* 1 \leq N \leq 200,000
* 1 \leq Q \leq 200,000
* 0 \leq u_i, v_i \lt N
Input
Input is given from Standard Input in the following format:
N Q
t_1 u_1 v_1
t_2 u_2 v_2
:
t_Q u_Q v_Q
出力
For each query of the latter type, print the answer.
Example
Input
4 7
1 0 1
0 0 1
0 2 3
1 0 1
1 1 2
0 0 2
1 1 3
Output
0
1
0
1
Submitted Solution:
```
#![allow(unused_imports, non_snake_case, dead_code)]
use proconio::{
input, fastout,
marker::{Chars, Bytes, Usize1}
};
struct UnionFind {
size: usize,
pos: Vec<isize>,
}
impl UnionFind {
fn new(n: usize) -> Self {
let size = n;
let pos = vec![-1; n + 1];
UnionFind { size, pos }
}
fn find(&mut self, x: usize) -> usize {
if self.pos[x] < 0 {
x
} else {
let v = self.pos[x] as usize;
self.pos[x] = self.find(v) as isize;
self.pos[x] as usize
}
}
fn unite(&mut self, x: usize, y: usize) -> Result<(), ()> {
let mut x = self.find(x);
let mut y = self.find(y);
if x == y {
return Err(());
};
if self.pos[x] > self.pos[y] {
std::mem::swap(&mut x, &mut y);
}
self.pos[x] += self.pos[y];
self.pos[y] = x as isize;
Ok(())
}
fn same(&mut self, x: usize, y: usize) -> bool {
self.find(x) == self.find(y)
}
fn size(&mut self, x: usize) -> usize {
let x = self.find(x);
-self.pos[x] as usize
}
}
#[fastout]
fn main() {
input! {
N: usize, Q: usize,
l: [(usize, usize, usize); Q]
}
let mut uf = UnionFind::new(N);
for &(t, x, y) in &l {
if t > 0 {
println!("{}", if uf.same(x, y) {1} else {0});
} else {
uf.unite(x,y).ok();
}
}
// println!("{}", N);
}
``` | instruction | 0 | 37,506 | 13 | 75,012 |
No | output | 1 | 37,506 | 13 | 75,013 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Build an undirected graph with N vertices with indices 1 to N that satisfies the following two conditions:
* The graph is simple and connected.
* There exists an integer S such that, for every vertex, the sum of the indices of the vertices adjacent to that vertex is S.
It can be proved that at least one such graph exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
In the first line, print the number of edges, M, in the graph you made. In the i-th of the following M lines, print two integers a_i and b_i, representing the endpoints of the i-th edge.
The output will be judged correct if the graph satisfies the conditions.
Example
Input
3
Output
2
1 3
2 3 | instruction | 0 | 37,555 | 13 | 75,110 |
"Correct Solution:
```
n=int(input())
ans=[]
for i in range(1,n):
for j in range(i+1,n+1):
ans.append([i,j])
if(n%2==1):
m=(n-1)**2//2
for i in range(1,n//2+1):
ans.remove([i,n-i])
else:
m=n*(n-2)//2
for i in range(1,n//2+1):
ans.remove([i,n+1-i])
print(m)
for i in ans:
print(str(i[0])+" "+str(i[1]))
``` | output | 1 | 37,555 | 13 | 75,111 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Build an undirected graph with N vertices with indices 1 to N that satisfies the following two conditions:
* The graph is simple and connected.
* There exists an integer S such that, for every vertex, the sum of the indices of the vertices adjacent to that vertex is S.
It can be proved that at least one such graph exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
In the first line, print the number of edges, M, in the graph you made. In the i-th of the following M lines, print two integers a_i and b_i, representing the endpoints of the i-th edge.
The output will be judged correct if the graph satisfies the conditions.
Example
Input
3
Output
2
1 3
2 3 | instruction | 0 | 37,556 | 13 | 75,112 |
"Correct Solution:
```
N = int(input())
M = N * (N - 1) // 2 - N // 2
S = N // 2 * 2 + 1
print(M)
for i in range(1, N):
for j in range(i + 1, N + 1):
if i + j == S:
continue
print(i, j)
``` | output | 1 | 37,556 | 13 | 75,113 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Build an undirected graph with N vertices with indices 1 to N that satisfies the following two conditions:
* The graph is simple and connected.
* There exists an integer S such that, for every vertex, the sum of the indices of the vertices adjacent to that vertex is S.
It can be proved that at least one such graph exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
In the first line, print the number of edges, M, in the graph you made. In the i-th of the following M lines, print two integers a_i and b_i, representing the endpoints of the i-th edge.
The output will be judged correct if the graph satisfies the conditions.
Example
Input
3
Output
2
1 3
2 3 | instruction | 0 | 37,557 | 13 | 75,114 |
"Correct Solution:
```
N = int(input())
ans = []
M = N + 1 * (N % 2 == 0)
for i in range(1, N + 1):
for j in range(i + 1, N + 1):
if i + j == M:
continue
ans.append('{} {}'.format(i, j))
print(len(ans))
print('\n'.join(ans))
``` | output | 1 | 37,557 | 13 | 75,115 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Build an undirected graph with N vertices with indices 1 to N that satisfies the following two conditions:
* The graph is simple and connected.
* There exists an integer S such that, for every vertex, the sum of the indices of the vertices adjacent to that vertex is S.
It can be proved that at least one such graph exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
In the first line, print the number of edges, M, in the graph you made. In the i-th of the following M lines, print two integers a_i and b_i, representing the endpoints of the i-th edge.
The output will be judged correct if the graph satisfies the conditions.
Example
Input
3
Output
2
1 3
2 3 | instruction | 0 | 37,558 | 13 | 75,116 |
"Correct Solution:
```
from itertools import combinations
n=int(input())
A=[]
num=n if n%2==1 else n+1
for a,b in combinations([j+1 for j in range(n)],2):
if a+b!=num:A.append([a,b])
print(len(A))
for i in A:print(*i)
``` | output | 1 | 37,558 | 13 | 75,117 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Build an undirected graph with N vertices with indices 1 to N that satisfies the following two conditions:
* The graph is simple and connected.
* There exists an integer S such that, for every vertex, the sum of the indices of the vertices adjacent to that vertex is S.
It can be proved that at least one such graph exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
In the first line, print the number of edges, M, in the graph you made. In the i-th of the following M lines, print two integers a_i and b_i, representing the endpoints of the i-th edge.
The output will be judged correct if the graph satisfies the conditions.
Example
Input
3
Output
2
1 3
2 3 | instruction | 0 | 37,559 | 13 | 75,118 |
"Correct Solution:
```
N = int(input())
cnt = 0
A = []
for u in range(1, N) :
for v in range(u+1, N+1) :
if u + v == N + (N % 2 != 1) :
continue
else :
cnt += 1
A.append((u, v))
print(cnt)
for i in range(cnt) :
print(*A[i])
``` | output | 1 | 37,559 | 13 | 75,119 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Build an undirected graph with N vertices with indices 1 to N that satisfies the following two conditions:
* The graph is simple and connected.
* There exists an integer S such that, for every vertex, the sum of the indices of the vertices adjacent to that vertex is S.
It can be proved that at least one such graph exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
In the first line, print the number of edges, M, in the graph you made. In the i-th of the following M lines, print two integers a_i and b_i, representing the endpoints of the i-th edge.
The output will be judged correct if the graph satisfies the conditions.
Example
Input
3
Output
2
1 3
2 3 | instruction | 0 | 37,560 | 13 | 75,120 |
"Correct Solution:
```
N = int(input())
ban = N if N%2 else N+1
ans = []
for i in range(1,N):
for j in range(i+1,N+1):
if i+j == ban: continue
ans.append(str(i) + ' ' + str(j))
print(len(ans))
print(*ans, sep='\n')
``` | output | 1 | 37,560 | 13 | 75,121 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Build an undirected graph with N vertices with indices 1 to N that satisfies the following two conditions:
* The graph is simple and connected.
* There exists an integer S such that, for every vertex, the sum of the indices of the vertices adjacent to that vertex is S.
It can be proved that at least one such graph exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
In the first line, print the number of edges, M, in the graph you made. In the i-th of the following M lines, print two integers a_i and b_i, representing the endpoints of the i-th edge.
The output will be judged correct if the graph satisfies the conditions.
Example
Input
3
Output
2
1 3
2 3 | instruction | 0 | 37,561 | 13 | 75,122 |
"Correct Solution:
```
N=int(input())
if N%2==0:
print(N*(N-2)//2)
for i in range(1,N+1):
for j in range(i+1,N+1):
if i+j!=N+1:
print(i,j)
else:
print(((N-1)*(N-3))//2+N-1)
for i in range(1,N+1):
for j in range(i+1,N+1):
if i+j!=N:
print(i,j)
``` | output | 1 | 37,561 | 13 | 75,123 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Build an undirected graph with N vertices with indices 1 to N that satisfies the following two conditions:
* The graph is simple and connected.
* There exists an integer S such that, for every vertex, the sum of the indices of the vertices adjacent to that vertex is S.
It can be proved that at least one such graph exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
In the first line, print the number of edges, M, in the graph you made. In the i-th of the following M lines, print two integers a_i and b_i, representing the endpoints of the i-th edge.
The output will be judged correct if the graph satisfies the conditions.
Example
Input
3
Output
2
1 3
2 3 | instruction | 0 | 37,562 | 13 | 75,124 |
"Correct Solution:
```
N = int(input())
print(N*(N-1)//2 - N//2)
if(N%2 == 0):
for i in range(1,N):
for j in range(i+1,N+1):
if(i+j != N+1):
print(*[i,j])
else:
for i in range(1,N):
for j in range(i+1,N+1):
if(i+j != N):
print(*[i,j])
``` | output | 1 | 37,562 | 13 | 75,125 |
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. Build an undirected graph with N vertices with indices 1 to N that satisfies the following two conditions:
* The graph is simple and connected.
* There exists an integer S such that, for every vertex, the sum of the indices of the vertices adjacent to that vertex is S.
It can be proved that at least one such graph exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
In the first line, print the number of edges, M, in the graph you made. In the i-th of the following M lines, print two integers a_i and b_i, representing the endpoints of the i-th edge.
The output will be judged correct if the graph satisfies the conditions.
Example
Input
3
Output
2
1 3
2 3
Submitted Solution:
```
N = int(input())
even = True if N % 2 == 0 else False
print(N*(N-1)//2-N//2)
for i in range(1, N):
for j in range(i+1, N+1):
if even and i + j != N+1 or not even and i + j != N:
print(i, j)
``` | instruction | 0 | 37,563 | 13 | 75,126 |
Yes | output | 1 | 37,563 | 13 | 75,127 |
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. Build an undirected graph with N vertices with indices 1 to N that satisfies the following two conditions:
* The graph is simple and connected.
* There exists an integer S such that, for every vertex, the sum of the indices of the vertices adjacent to that vertex is S.
It can be proved that at least one such graph exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
In the first line, print the number of edges, M, in the graph you made. In the i-th of the following M lines, print two integers a_i and b_i, representing the endpoints of the i-th edge.
The output will be judged correct if the graph satisfies the conditions.
Example
Input
3
Output
2
1 3
2 3
Submitted Solution:
```
N = int(input())
ans = []
for i in range(1,N+1):
for j in range(i+1,N+1):
if N % 2 == 0 and i+j == N+1: continue
if N % 2 == 1 and i+j == N: continue
ans.append([i,j])
print(len(ans))
for a in ans:
print(a[0],a[1])
``` | instruction | 0 | 37,564 | 13 | 75,128 |
Yes | output | 1 | 37,564 | 13 | 75,129 |
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. Build an undirected graph with N vertices with indices 1 to N that satisfies the following two conditions:
* The graph is simple and connected.
* There exists an integer S such that, for every vertex, the sum of the indices of the vertices adjacent to that vertex is S.
It can be proved that at least one such graph exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
In the first line, print the number of edges, M, in the graph you made. In the i-th of the following M lines, print two integers a_i and b_i, representing the endpoints of the i-th edge.
The output will be judged correct if the graph satisfies the conditions.
Example
Input
3
Output
2
1 3
2 3
Submitted Solution:
```
n = int(input())
if n % 2 == 0:
nn = n
print(n*(n-2)//2)
else:
nn = n-1
print(nn*(nn-2)//2+nn)
for i in range(1,nn//2):
for j in range(i+1,nn//2 + 1):
print(i,j)
print(i,nn+1-j)
print(nn+1-i,j)
print(nn+1-i,nn+1-j)
if n % 2 == 1:
for i in range(1,n):
print(i,n)
``` | instruction | 0 | 37,565 | 13 | 75,130 |
Yes | output | 1 | 37,565 | 13 | 75,131 |
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. Build an undirected graph with N vertices with indices 1 to N that satisfies the following two conditions:
* The graph is simple and connected.
* There exists an integer S such that, for every vertex, the sum of the indices of the vertices adjacent to that vertex is S.
It can be proved that at least one such graph exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
In the first line, print the number of edges, M, in the graph you made. In the i-th of the following M lines, print two integers a_i and b_i, representing the endpoints of the i-th edge.
The output will be judged correct if the graph satisfies the conditions.
Example
Input
3
Output
2
1 3
2 3
Submitted Solution:
```
n = int(input())
al = int(n * (n - 1)/2)
alls = []
for k in range(1,n+1):
for i in range(k+1,n+1):
alls.append((k,i))
if n%2 == 1:
for k in range(1, (n-1)//2 + 1):
alls.remove((k, n-k))
else:
for k in range(1,(n//2) +1):
alls.remove((k,n-k+1))
print(len(alls))
for a in alls:
print(a[0], a[1])
``` | instruction | 0 | 37,566 | 13 | 75,132 |
Yes | output | 1 | 37,566 | 13 | 75,133 |
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. Build an undirected graph with N vertices with indices 1 to N that satisfies the following two conditions:
* The graph is simple and connected.
* There exists an integer S such that, for every vertex, the sum of the indices of the vertices adjacent to that vertex is S.
It can be proved that at least one such graph exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
In the first line, print the number of edges, M, in the graph you made. In the i-th of the following M lines, print two integers a_i and b_i, representing the endpoints of the i-th edge.
The output will be judged correct if the graph satisfies the conditions.
Example
Input
3
Output
2
1 3
2 3
Submitted Solution:
```
def main():
N = int(input())
edges = []
M = N*(N-1)//2 - N//2
if N%2 == 1:
for i in range(1, N):
for j in range(i+1, N+1):
if i + j != N:
edges.append((i, j))
else:
for i in range(1, N):
for j in range(i, N+1):
if i + j != N + 1:
edges.append((i, j))
print(M)
for a, b in edges:
print(a, b)
if __name__ == "__main__":
main()
``` | instruction | 0 | 37,567 | 13 | 75,134 |
No | output | 1 | 37,567 | 13 | 75,135 |
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. Build an undirected graph with N vertices with indices 1 to N that satisfies the following two conditions:
* The graph is simple and connected.
* There exists an integer S such that, for every vertex, the sum of the indices of the vertices adjacent to that vertex is S.
It can be proved that at least one such graph exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
In the first line, print the number of edges, M, in the graph you made. In the i-th of the following M lines, print two integers a_i and b_i, representing the endpoints of the i-th edge.
The output will be judged correct if the graph satisfies the conditions.
Example
Input
3
Output
2
1 3
2 3
Submitted Solution:
```
n = int(input())
if n%2 == 1:
a = n-1
else:
a = n
for i in range(a-1):
for j in range(i+1,a):
if i+j+2 == a+1:
continue
else:
print(i+1,j+1)
if n%2 == 1:
for i in range(n-1):
print(i+1,n)
``` | instruction | 0 | 37,568 | 13 | 75,136 |
No | output | 1 | 37,568 | 13 | 75,137 |
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. Build an undirected graph with N vertices with indices 1 to N that satisfies the following two conditions:
* The graph is simple and connected.
* There exists an integer S such that, for every vertex, the sum of the indices of the vertices adjacent to that vertex is S.
It can be proved that at least one such graph exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
In the first line, print the number of edges, M, in the graph you made. In the i-th of the following M lines, print two integers a_i and b_i, representing the endpoints of the i-th edge.
The output will be judged correct if the graph satisfies the conditions.
Example
Input
3
Output
2
1 3
2 3
Submitted Solution:
```
import sys
import re
import math
import collections
import bisect
import itertools
import fractions
import functools
import copy
import heapq
import decimal
import statistics
import queue
# import numpy as np
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 16
MOD = 10 ** 9 + 7
# MOD = 998244353
ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))
# ===CODE===
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()}
def __str__(self):
return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
def main():
n = ni()
ans = []
for i in range(n):
for j in range(i + 1, n):
if i + j + 2 != n + 1:
ans.append([i + 1, j + 1])
print(len(ans))
for a, b in ans:
print(a, b)
if __name__ == '__main__':
main()
``` | instruction | 0 | 37,569 | 13 | 75,138 |
No | output | 1 | 37,569 | 13 | 75,139 |
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. Build an undirected graph with N vertices with indices 1 to N that satisfies the following two conditions:
* The graph is simple and connected.
* There exists an integer S such that, for every vertex, the sum of the indices of the vertices adjacent to that vertex is S.
It can be proved that at least one such graph exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
In the first line, print the number of edges, M, in the graph you made. In the i-th of the following M lines, print two integers a_i and b_i, representing the endpoints of the i-th edge.
The output will be judged correct if the graph satisfies the conditions.
Example
Input
3
Output
2
1 3
2 3
Submitted Solution:
```
n = int(input())
if n % 2 == 0:
# 1 <-> n, 2 <-> n-1... is Pair
for i in range(1, n + 1):
for j in range(i + 1, n + 1):
if i + j != n + 1:
print(str(i) + " " + str(j))
else:
# Each edge has (sum - N)
for i in range(1, n + 1):
for j in range(i + 1, n + 1):
if i + j != n:
print(str(i) + " " + str(j))
``` | instruction | 0 | 37,570 | 13 | 75,140 |
No | output | 1 | 37,570 | 13 | 75,141 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n vertices. A number is written on each vertex; the number on vertex i is equal to a_i.
Let's denote the function g(x, y) as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex x to vertex y (including these two vertices). Also let's denote dist(x, y) as the number of vertices on the simple path between vertices x and y, including the endpoints. dist(x, x) = 1 for every vertex x.
Your task is calculate the maximum value of dist(x, y) among such pairs of vertices that g(x, y) > 1.
Input
The first line contains one integer n — the number of vertices (1 ≤ n ≤ 2 ⋅ 10^5).
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5) — the numbers written on vertices.
Then n - 1 lines follow, each containing two integers x and y (1 ≤ x, y ≤ n, x ≠ y) denoting an edge connecting vertex x with vertex y. It is guaranteed that these edges form a tree.
Output
If there is no pair of vertices x, y such that g(x, y) > 1, print 0. Otherwise print the maximum value of dist(x, y) among such pairs.
Examples
Input
3
2 3 4
1 2
2 3
Output
1
Input
3
2 3 4
1 3
2 3
Output
2
Input
3
1 1 1
1 2
2 3
Output
0 | instruction | 0 | 37,784 | 13 | 75,568 |
Tags: data structures, dfs and similar, dp, number theory, trees
Correct Solution:
```
import sys
answer = 1
z = True
primes = []
for i in range (2, 5 * 10 ** 2):
v = True
for p in primes:
if i % p == 0:
v = False
if v == True:
primes.append(i)
n = int(sys.stdin.readline().strip())
a = list(map(int, sys.stdin.readline().strip().split()))
if sum(a) == n:
z = False
for i in range (0, n):
x = a[i]
a[i] = []
for p in primes:
if x % p == 0:
a[i].append([p, 1])
x = x // p
while x % p == 0:
x = x // p
if x != 1:
a[i].append([x, 1])
neighbours = [[] for i in range (0, n)]
for i in range (0, n - 1):
line = sys.stdin.readline().strip().split()
neighbours[int(line[0]) - 1].append(int(line[1]) - 1)
neighbours[int(line[1]) - 1].append(int(line[0]) - 1)
leaves = []
for i in range (0, n):
if len(neighbours[i]) == 1:
leaves.append(i)
while len(leaves) > 1:
x = leaves.pop()
y = neighbours[x][0]
neighbours[y].remove(x)
if len(neighbours[y]) == 1:
leaves.append(y)
for p in a[x]:
for q in a[y]:
if p[0] == q[0]:
answer = max([answer, p[1] + q[1]])
q[1] = max([q[1],p[1]+1])
if z == False:
print(0)
else:
print(answer)
``` | output | 1 | 37,784 | 13 | 75,569 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n vertices. A number is written on each vertex; the number on vertex i is equal to a_i.
Let's denote the function g(x, y) as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex x to vertex y (including these two vertices). Also let's denote dist(x, y) as the number of vertices on the simple path between vertices x and y, including the endpoints. dist(x, x) = 1 for every vertex x.
Your task is calculate the maximum value of dist(x, y) among such pairs of vertices that g(x, y) > 1.
Input
The first line contains one integer n — the number of vertices (1 ≤ n ≤ 2 ⋅ 10^5).
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5) — the numbers written on vertices.
Then n - 1 lines follow, each containing two integers x and y (1 ≤ x, y ≤ n, x ≠ y) denoting an edge connecting vertex x with vertex y. It is guaranteed that these edges form a tree.
Output
If there is no pair of vertices x, y such that g(x, y) > 1, print 0. Otherwise print the maximum value of dist(x, y) among such pairs.
Examples
Input
3
2 3 4
1 2
2 3
Output
1
Input
3
2 3 4
1 3
2 3
Output
2
Input
3
1 1 1
1 2
2 3
Output
0 | instruction | 0 | 37,785 | 13 | 75,570 |
Tags: data structures, dfs and similar, dp, number theory, trees
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
from collections import defaultdict, deque, Counter, OrderedDict
import threading
def main():
ans = 1
flag = True
primes = []
for i in range(2, 500):
v = 1
for p in primes:
if i % p == 0: v = 0
if v: primes.append(i)
n = int(input())
a = [*map(int,input().split())]
if sum(a) == n: flag = False
for i in range(n):
x = a[i]
a[i] = []
for p in primes:
if x % p == 0:
a[i].append([p,1])
x = x//p
while x % p == 0: x //= p
if x != 1:a[i].append([x,1])
adj = [[] for i in range(n)]
for i in range(n-1):
x, y =map(int,input().split())
adj[x-1].append(y-1)
adj[y-1].append(x-1)
leaves = []
for i in range(n):
if len(adj[i]) == 1: leaves.append(i)
for i in range(n-1):
x = leaves.pop()
y = adj[x][0]
adj[y].remove(x)
if len(adj[y]) == 1: leaves.append(y)
for nx in a[x]:
for ny in a[y]:
if nx[0] == ny[0]:
ans = max([ans, nx[1] + ny[1]])
ny[1] = max([ny[1],nx[1]+1])
if not flag:print(0)
else:print(ans)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
"""sys.setrecursionlimit(400000)
threading.stack_size(40960000)
thread = threading.Thread(target=main)
thread.start()"""
main()
``` | output | 1 | 37,785 | 13 | 75,571 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n vertices. A number is written on each vertex; the number on vertex i is equal to a_i.
Let's denote the function g(x, y) as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex x to vertex y (including these two vertices). Also let's denote dist(x, y) as the number of vertices on the simple path between vertices x and y, including the endpoints. dist(x, x) = 1 for every vertex x.
Your task is calculate the maximum value of dist(x, y) among such pairs of vertices that g(x, y) > 1.
Input
The first line contains one integer n — the number of vertices (1 ≤ n ≤ 2 ⋅ 10^5).
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5) — the numbers written on vertices.
Then n - 1 lines follow, each containing two integers x and y (1 ≤ x, y ≤ n, x ≠ y) denoting an edge connecting vertex x with vertex y. It is guaranteed that these edges form a tree.
Output
If there is no pair of vertices x, y such that g(x, y) > 1, print 0. Otherwise print the maximum value of dist(x, y) among such pairs.
Examples
Input
3
2 3 4
1 2
2 3
Output
1
Input
3
2 3 4
1 3
2 3
Output
2
Input
3
1 1 1
1 2
2 3
Output
0 | instruction | 0 | 37,786 | 13 | 75,572 |
Tags: data structures, dfs and similar, dp, number theory, trees
Correct Solution:
```
import math
import sys
def get_primes(n):
result = set()
while n % 2 == 0:
result.add(2)
n = n / 2
for i in range(3, int(math.sqrt(n)) + 1, 2):
while n % i == 0:
result.add(i)
n = n / i
if n > 2:
result.add(n)
return list(result)
def calc(w, t, n):
stack = []
stack.append((t[0], dict([(p, [0]) for p in get_primes(w[0])])))
max_length = 0
visited = [False] * n
visited[0] = True
while stack:
if stack[-1][0]:
nxt = stack[-1][0][-1]
stack[-1][0].pop()
if visited[nxt]:
continue
else:
visited[nxt] = True
stack.append((t[nxt], dict([(p, [0]) for p in get_primes(w[nxt])])))
else:
last = stack[-1][1]
stack.pop()
if last:
max_length = max(max_length, 1 + max([sum(v) for _, v in last.items()]))
if stack:
for k, v in last.items():
if k in stack[-1][1].keys():
stack[-1][1][k].append(max(v) + 1)
stack[-1][1][k].sort(reverse=True)
if len(stack[-1][1][k]) > 2:
del stack[-1][1][k][-1]
return max_length
# if __name__ == '__main__':
# print(primeFactors(100))
if __name__ == '__main__':
n = int(input())
weights = list(map(int, input().split()))
lines = sys.stdin.readlines()
tree = [[] for _ in range(n)]
for line in lines:
x, y = map(int, line.split())
tree[x - 1].append(y - 1)
tree[y - 1].append(x - 1)
print(calc(weights, tree, n))
``` | output | 1 | 37,786 | 13 | 75,573 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n vertices. A number is written on each vertex; the number on vertex i is equal to a_i.
Let's denote the function g(x, y) as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex x to vertex y (including these two vertices). Also let's denote dist(x, y) as the number of vertices on the simple path between vertices x and y, including the endpoints. dist(x, x) = 1 for every vertex x.
Your task is calculate the maximum value of dist(x, y) among such pairs of vertices that g(x, y) > 1.
Input
The first line contains one integer n — the number of vertices (1 ≤ n ≤ 2 ⋅ 10^5).
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5) — the numbers written on vertices.
Then n - 1 lines follow, each containing two integers x and y (1 ≤ x, y ≤ n, x ≠ y) denoting an edge connecting vertex x with vertex y. It is guaranteed that these edges form a tree.
Output
If there is no pair of vertices x, y such that g(x, y) > 1, print 0. Otherwise print the maximum value of dist(x, y) among such pairs.
Examples
Input
3
2 3 4
1 2
2 3
Output
1
Input
3
2 3 4
1 3
2 3
Output
2
Input
3
1 1 1
1 2
2 3
Output
0 | instruction | 0 | 37,787 | 13 | 75,574 |
Tags: data structures, dfs and similar, dp, number theory, trees
Correct Solution:
```
from collections import deque
import sys
from array import array # noqa: F401
import typing as Tp # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
def get_primes(n: int):
from itertools import chain
primes = [2, 3]
is_prime = (array('b', (0, 0, 1, 1, 0, 1, 0))
+ array('b', (1, 0, 0, 0, 1, 0)) * ((n - 1) // 6))
for i in chain.from_iterable((range(5, n + 1, 6), range(7, n + 1, 6))):
if is_prime[i]:
primes.append(i)
for j in range(i * 3, n + 1, i * 2):
is_prime[j] = 0
return is_prime, primes
def solve(adj, start, p, visited, a):
dq = deque([start])
visited[start] = 1
leaf = start
while dq:
leaf = v = dq.popleft()
for dest in adj[v]:
if visited[dest] == 0 and (a[dest] % p == 0 if p > 0 else a[dest] == -p):
visited[dest] = 1
dq.append(dest)
dq = deque([(leaf, 1)])
visited[leaf] = 2
while dq:
v, res = dq.popleft()
for dest in adj[v]:
if visited[dest] == 1 and (a[dest] % p == 0 if p > 0 else a[dest] == -p):
visited[dest] = 2
dq.append((dest, res + 1))
return res
def main():
n = int(input())
a = list(map(int, input().split()))
adj = [[] for _ in range(n)]
for u, v in (map(int, input().split()) for _ in range(n - 1)):
adj[u - 1].append(v - 1)
adj[v - 1].append(u - 1)
ans = 0
_, primes = get_primes(448)
for p in primes:
visited = [0] * n
for i in range(n):
if visited[i] or a[i] % p:
continue
ans = max(ans, solve(adj, i, p, visited, a))
visited = [0] * n
for i in range(n):
if visited[i] or a[i] == 1:
continue
ans = max(ans, solve(adj, i, -a[i], visited, a))
print(ans)
if __name__ == '__main__':
main()
``` | output | 1 | 37,787 | 13 | 75,575 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n vertices. A number is written on each vertex; the number on vertex i is equal to a_i.
Let's denote the function g(x, y) as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex x to vertex y (including these two vertices). Also let's denote dist(x, y) as the number of vertices on the simple path between vertices x and y, including the endpoints. dist(x, x) = 1 for every vertex x.
Your task is calculate the maximum value of dist(x, y) among such pairs of vertices that g(x, y) > 1.
Input
The first line contains one integer n — the number of vertices (1 ≤ n ≤ 2 ⋅ 10^5).
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5) — the numbers written on vertices.
Then n - 1 lines follow, each containing two integers x and y (1 ≤ x, y ≤ n, x ≠ y) denoting an edge connecting vertex x with vertex y. It is guaranteed that these edges form a tree.
Output
If there is no pair of vertices x, y such that g(x, y) > 1, print 0. Otherwise print the maximum value of dist(x, y) among such pairs.
Examples
Input
3
2 3 4
1 2
2 3
Output
1
Input
3
2 3 4
1 3
2 3
Output
2
Input
3
1 1 1
1 2
2 3
Output
0 | instruction | 0 | 37,788 | 13 | 75,576 |
Tags: data structures, dfs and similar, dp, number theory, trees
Correct Solution:
```
from sys import stdin, stdout
from math import *
from heapq import *
from collections import *
dv=list(range(200002))
for i in range(2,200002):
if ((i*i)>=200002):
break
if (dv[i]==i):
j=i
while ((i*j)<200002):
dv[i*j]=i
j=j+1
def loPr(x):
global dv
if (x<=1):
return []
ret=[]
while(x>1):
d=dv[x]
ret.append(d)
while(x%d==0):
x=trunc(x/d)
return ret
def main():
global dv
n=int(stdin.readline())
a=[0]+[int(x) for x in stdin.readline().split()]
e=[]
for _ in range(n+2):
e.append([])
for _ in range(n-1):
u,v=[int(x) for x in stdin.readline().split()]
e[u].append(v)
e[v].append(u)
pre=[0]*(n+2)
q=[1]
d=[False]*(n+2)
d[1]=True
pre[1]=1
i=0
while(i<len(q)):
u=q[i]
for v in e[u]:
if (d[v]==False):
d[v]=True
pre[v]=u
q.append(v)
i=i+1
f=[dict()]
for _ in range(n+2):
f.append(dict())
b=[[]]
for i in range(1,n+1):
b.append(loPr(a[i]))
for p in b[i]:
f[i][p]=[1]
q.reverse()
res=0
for u in q:
nxt=pre[u]
#print (str(u)+": f=" +str(f[u])+ " b=" +str(b[u]))
for p in b[u]:
fp=f[u].get(p,[1])
fp.sort()
res=max(res,fp[-1])
if (len(fp)>=2):
res=max(res,fp[-1]+fp[-2]-1)
fnxt=f[nxt].get(p,None)
if (fnxt!=None):
fnxt.append(max(1,fp[-1])+1)
stdout.write(str(res))
return 0
if __name__ == "__main__":
main()
``` | output | 1 | 37,788 | 13 | 75,577 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n vertices. A number is written on each vertex; the number on vertex i is equal to a_i.
Let's denote the function g(x, y) as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex x to vertex y (including these two vertices). Also let's denote dist(x, y) as the number of vertices on the simple path between vertices x and y, including the endpoints. dist(x, x) = 1 for every vertex x.
Your task is calculate the maximum value of dist(x, y) among such pairs of vertices that g(x, y) > 1.
Input
The first line contains one integer n — the number of vertices (1 ≤ n ≤ 2 ⋅ 10^5).
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5) — the numbers written on vertices.
Then n - 1 lines follow, each containing two integers x and y (1 ≤ x, y ≤ n, x ≠ y) denoting an edge connecting vertex x with vertex y. It is guaranteed that these edges form a tree.
Output
If there is no pair of vertices x, y such that g(x, y) > 1, print 0. Otherwise print the maximum value of dist(x, y) among such pairs.
Examples
Input
3
2 3 4
1 2
2 3
Output
1
Input
3
2 3 4
1 3
2 3
Output
2
Input
3
1 1 1
1 2
2 3
Output
0 | instruction | 0 | 37,789 | 13 | 75,578 |
Tags: data structures, dfs and similar, dp, number theory, trees
Correct Solution:
```
from collections import deque
# from time import time
# tt = time()
n = int(input())
a = [0] + list(map(int, input().split()))
e = [[] for i in range(n + 1)]
for i in range(n - 1):
u, v = map(int, input().split())
e[u].append(v)
e[v].append(u)
# print(e)
# find all primes
isp = [1] * 501
prime = []
for i in range(2, 501):
if isp[i]:
prime.append(i)
for p in prime:
if i * p > 500:
break
isp[i * p] = 0
if i % p == 0:
break
lp = len(prime)
# gr is a forest, n is # of vertices
def diam(gr, n):
vis = [0] * (n + 1)
lvl = [-1] * (n + 1)
maxlvl = 0
for i in range(1, n + 1):
if not vis[i]:
q = deque([i])
start = i
while q:
start = q.popleft()
for to in gr[start]:
if not vis[to]:
vis[to] = 1
q.append(to)
q.append(start)
# print(start)
lvl[start] = 0
tmplvl = 0
while q:
cur = q.popleft()
for to in gr[cur]:
if lvl[to] == -1:
lvl[to] = lvl[cur] + 1
q.append(to)
tmplvl = lvl[to]
maxlvl = max(maxlvl, tmplvl)
return maxlvl + 1
# print('input', time() - tt)
# tt = time()
newn = [0] * (n + 1)
# find vertices in each graph
v = [[] for i in range(lp)]
other = {}
for i in range(1, n + 1):
l = a[i]
for j in range(lp):
r = prime[j]
if l % r == 0:
v[j].append(i)
while l % r == 0:
l //= r
if l != 1:
if l in other:
other[l].append(i)
else:
other[l] = [i]
for val in other.values():
v.append(val)
ans = 0
# build the graph
for i in range(len(v)):
count = 1
for node in v[i]:
newn[node] = count
count += 1
if count == 1:
continue
g = [[] for i in range(count)]
for node in v[i]:
for to in e[node]:
if newn[to]:
g[newn[node]].append(newn[to])
ans = max(ans, diam(g, count - 1))
for node in v[i]:
newn[node] = 0
print(ans)
``` | output | 1 | 37,789 | 13 | 75,579 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree consisting of n vertices. A number is written on each vertex; the number on vertex i is equal to a_i.
Let's denote the function g(x, y) as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex x to vertex y (including these two vertices). Also let's denote dist(x, y) as the number of vertices on the simple path between vertices x and y, including the endpoints. dist(x, x) = 1 for every vertex x.
Your task is calculate the maximum value of dist(x, y) among such pairs of vertices that g(x, y) > 1.
Input
The first line contains one integer n — the number of vertices (1 ≤ n ≤ 2 ⋅ 10^5).
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5) — the numbers written on vertices.
Then n - 1 lines follow, each containing two integers x and y (1 ≤ x, y ≤ n, x ≠ y) denoting an edge connecting vertex x with vertex y. It is guaranteed that these edges form a tree.
Output
If there is no pair of vertices x, y such that g(x, y) > 1, print 0. Otherwise print the maximum value of dist(x, y) among such pairs.
Examples
Input
3
2 3 4
1 2
2 3
Output
1
Input
3
2 3 4
1 3
2 3
Output
2
Input
3
1 1 1
1 2
2 3
Output
0
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
from collections import defaultdict, deque, Counter, OrderedDict
import threading
def main():
ans = 1
flag = True
primes = []
for i in range(2, 500):
v = 1
for p in primes:
if i % p == 0: v = 0
if v: primes.append(i)
n = int(input())
a = [*map(int,input().split())]
if sum(a) == n: flag = False
for i in range(n):
x = a[i]
a[i] = []
for p in primes:
if x % p == 0:
a[i].append([p,1])
x = x//p
while x % p == 0: x //= p
a[i].append([x,1])
adj = [[] for i in range(n)]
for i in range(n-1):
x, y =map(int,input().split())
adj[x-1].append(y-1)
adj[y-1].append(x-1)
leaves = []
for i in range(n):
if len(adj[i]) == 1: leaves.append(i)
for i in range(n-1):
x = leaves.pop()
y = adj[x][0]
adj[y].remove(x)
if len(adj[y]) == 1: leaves.append(y)
for nx in a[x]:
for ny in a[y]:
if nx[0] == ny[0]:
ans = max([ans, nx[1] + ny[1]])
ny[1] = max([ny[1],nx[1]+1])
if not flag:print(0)
else:print(ans)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
"""sys.setrecursionlimit(400000)
threading.stack_size(40960000)
thread = threading.Thread(target=main)
thread.start()"""
main()
``` | instruction | 0 | 37,790 | 13 | 75,580 |
No | output | 1 | 37,790 | 13 | 75,581 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree consisting of n vertices. A number is written on each vertex; the number on vertex i is equal to a_i.
Let's denote the function g(x, y) as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex x to vertex y (including these two vertices). Also let's denote dist(x, y) as the number of vertices on the simple path between vertices x and y, including the endpoints. dist(x, x) = 1 for every vertex x.
Your task is calculate the maximum value of dist(x, y) among such pairs of vertices that g(x, y) > 1.
Input
The first line contains one integer n — the number of vertices (1 ≤ n ≤ 2 ⋅ 10^5).
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5) — the numbers written on vertices.
Then n - 1 lines follow, each containing two integers x and y (1 ≤ x, y ≤ n, x ≠ y) denoting an edge connecting vertex x with vertex y. It is guaranteed that these edges form a tree.
Output
If there is no pair of vertices x, y such that g(x, y) > 1, print 0. Otherwise print the maximum value of dist(x, y) among such pairs.
Examples
Input
3
2 3 4
1 2
2 3
Output
1
Input
3
2 3 4
1 3
2 3
Output
2
Input
3
1 1 1
1 2
2 3
Output
0
Submitted Solution:
```
# problem http://codeforces.com/contest/1101/problem/D
import sys
def get_primes(n):
result = set()
for i in range(2, n):
while n % i == 0:
# print i,"|",n
n = n / i
result.add(i)
if n == 1:
break
if n > 1: result.add(n)
return list(result)
def calc(w, t, n):
stack = []
stack.append((t[0], dict([(p, [0]) for p in get_primes(w[0])])))
max_length = 0
visited = [False] * n
visited[0] = True
while stack:
if stack[-1][0]:
nxt = stack[-1][0][-1]
stack[-1][0].pop()
if visited[nxt]:
continue
else:
visited[nxt] = True
stack.append((t[nxt], dict([(p, [0]) for p in get_primes(w[nxt])])))
else:
last = stack[-1][1]
stack.pop()
if last:
max_length = max(max_length, 1 + max([sum(v) for _, v in last.items()]))
if stack:
for k, v in last.items():
if k in stack[-1][1].keys():
stack[-1][1][k].append(max(v) + 1)
stack[-1][1][k].sort(reverse=True)
del stack[-1][1][k][-1]
return max_length
if __name__ == '__main__1':
print(get_primes(100))
if __name__ == '__main__':
n = int(input())
weights = list(map(int, input().split()))
lines = sys.stdin.readlines()
tree = [[] for _ in range(n)]
for line in lines:
x, y = map(int, line.split())
tree[x - 1].append(y - 1)
tree[y - 1].append(x - 1)
print(calc(weights, tree, n))
``` | instruction | 0 | 37,791 | 13 | 75,582 |
No | output | 1 | 37,791 | 13 | 75,583 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree consisting of n vertices. A number is written on each vertex; the number on vertex i is equal to a_i.
Let's denote the function g(x, y) as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex x to vertex y (including these two vertices). Also let's denote dist(x, y) as the number of vertices on the simple path between vertices x and y, including the endpoints. dist(x, x) = 1 for every vertex x.
Your task is calculate the maximum value of dist(x, y) among such pairs of vertices that g(x, y) > 1.
Input
The first line contains one integer n — the number of vertices (1 ≤ n ≤ 2 ⋅ 10^5).
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5) — the numbers written on vertices.
Then n - 1 lines follow, each containing two integers x and y (1 ≤ x, y ≤ n, x ≠ y) denoting an edge connecting vertex x with vertex y. It is guaranteed that these edges form a tree.
Output
If there is no pair of vertices x, y such that g(x, y) > 1, print 0. Otherwise print the maximum value of dist(x, y) among such pairs.
Examples
Input
3
2 3 4
1 2
2 3
Output
1
Input
3
2 3 4
1 3
2 3
Output
2
Input
3
1 1 1
1 2
2 3
Output
0
Submitted Solution:
```
from collections import deque
# from time import time
# tt = time()
n = int(input())
a = [0] + list(map(int, input().split()))
e = [[] for i in range(n + 1)]
for i in range(n - 1):
u, v = map(int, input().split())
e[u].append(v)
e[v].append(u)
# print(e)
# find all primes
isp = [1] * 501
prime = []
for i in range(2, 501):
if isp[i]:
prime.append(i)
for p in prime:
if i * p > 500:
break
isp[i * p] = 0
if i % p == 0:
break
lp = len(prime)
# gr is a forest, n is # of vertices
def diam(gr, n):
vis = [0] * (n + 1)
lvl = [-1] * (n + 1)
maxlvl = 0
for i in range(1, n + 1):
if not vis[i]:
q = deque([i])
start = i
while q:
start = q.popleft()
for to in gr[start]:
if not vis[to]:
vis[to] = 1
q.append(to)
q.append(start)
# print(start)
lvl[start] = 0
tmplvl = 0
while q:
cur = q.popleft()
for to in gr[cur]:
if lvl[to] == -1:
lvl[to] = lvl[cur] + 1
q.append(to)
tmplvl = lvl[to]
maxlvl = max(maxlvl, tmplvl)
# print(lvl)
return maxlvl + 1
# print('input', time() - tt)
# tt = time()
newn = [0] * (n + 1)
# find vertices in each graph
v = [[] for i in range(lp)]
other = {}
for i in range(1, n + 1):
l = a[i]
for j in range(lp):
r = prime[j]
if l % r == 0:
v[j].append(i)
while l % r == 0:
l //= r
if l != 1:
if l in other:
other[l].append(i)
else:
other[l] = [i]
for val in other.values():
v.append(val)
# print(v)
# print('fenlei', time() - tt)
# tt = time()
ans = 0
# build the graph
for i in range(len(v)):
# if i % 100 == 0:
# print(i)
count = 1
for node in v[i]:
newn[node] = count
count += 1
if count == 1:
continue
g = [[] for i in range(count)]
for node in v[i]:
for to in e[node]:
if newn[to]:
g[newn[node]].append(newn[to])
# print(newn, g)
ans = max(ans, diam(g, count - 1))
for node in v[i]:
newn[node] = 0
print(ans)
``` | instruction | 0 | 37,792 | 13 | 75,584 |
No | output | 1 | 37,792 | 13 | 75,585 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree consisting of n vertices. A number is written on each vertex; the number on vertex i is equal to a_i.
Let's denote the function g(x, y) as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex x to vertex y (including these two vertices). Also let's denote dist(x, y) as the number of vertices on the simple path between vertices x and y, including the endpoints. dist(x, x) = 1 for every vertex x.
Your task is calculate the maximum value of dist(x, y) among such pairs of vertices that g(x, y) > 1.
Input
The first line contains one integer n — the number of vertices (1 ≤ n ≤ 2 ⋅ 10^5).
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5) — the numbers written on vertices.
Then n - 1 lines follow, each containing two integers x and y (1 ≤ x, y ≤ n, x ≠ y) denoting an edge connecting vertex x with vertex y. It is guaranteed that these edges form a tree.
Output
If there is no pair of vertices x, y such that g(x, y) > 1, print 0. Otherwise print the maximum value of dist(x, y) among such pairs.
Examples
Input
3
2 3 4
1 2
2 3
Output
1
Input
3
2 3 4
1 3
2 3
Output
2
Input
3
1 1 1
1 2
2 3
Output
0
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
from collections import defaultdict, deque, Counter, OrderedDict
import threading
def main():
ans = 1
flag = True
primes = []
for i in range(2, 500):
v = 1
for p in primes:
if i % p == 0: v = 0
if v: primes.append(i)
n = int(input())
a = [*map(int,input().split())]
if sum(a) == n: flag = False
for i in range(n):
x = a[i]
a[i] = []
for p in primes:
if x % p == 0:
a[i].append([p,1])
x = x//p
while x % p == 0: x //= p
if x != 1:a[i].append([x,1])
adj = [[] for i in range(n)]
for i in range(n-1):
x, y =map(int,input().split())
adj[x-1].append(y-1)
adj[y-1].append(x-1)
leaves = []
for i in range(n):
if len(adj[i]) == 1: leaves.append(i)
for i in range(n-1):
x = leaves.pop()
y = adj[x][0]
adj[y].remove(x)
if len(adj[y]) == 1: leaves.append(y)
for nx in a[x]:
for ny in a[y]:
print(nx,ny)
if nx[0] == ny[0]:
ans = max([ans, nx[1] + ny[1]])
ny[1] = max([ny[1],nx[1]+1])
if not flag:print(0)
else:print(ans)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
"""sys.setrecursionlimit(400000)
threading.stack_size(40960000)
thread = threading.Thread(target=main)
thread.start()"""
main()
``` | instruction | 0 | 37,793 | 13 | 75,586 |
No | output | 1 | 37,793 | 13 | 75,587 |
Provide tags and a correct Python 3 solution for this coding contest problem.
PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.
There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.
How many trees are there in the forest?
Input
The first line contains single integer n (1 ≤ n ≤ 104) — the number of Balls living in the forest.
The second line contains a sequence p1, p2, ..., pn of length n, where (1 ≤ pi ≤ n) holds and pi denotes the most distant from Ball i relative living on the same tree. If there are several most distant relatives living on the same tree, pi is the id of one with the smallest id.
It's guaranteed that the sequence p corresponds to some valid forest.
Hacking: To hack someone, you should provide a correct forest as a test. The sequence p will be calculated according to the forest and given to the solution you try to hack as input. Use the following format:
In the first line, output the integer n (1 ≤ n ≤ 104) — the number of Balls and the integer m (0 ≤ m < n) — the total number of edges in the forest. Then m lines should follow. The i-th of them should contain two integers ai and bi and represent an edge between vertices in which relatives ai and bi live. For example, the first sample is written as follows:
5 3
1 2
3 4
4 5
Output
You should output the number of trees in the forest where PolandBall lives.
Interaction
From the technical side, this problem is interactive. However, it should not affect you (except hacking) since there is no interaction.
Examples
Input
5
2 1 5 3 3
Output
2
Input
1
1
Output
1
Note
In the first sample testcase, possible forest is: 1-2 3-4-5.
There are 2 trees overall.
In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree. | instruction | 0 | 38,191 | 13 | 76,382 |
Tags: dfs and similar, dsu, graphs, interactive, trees
Correct Solution:
```
#dfs and similar, dsu, graphs, interactive, trees
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self, fr, to):
self.graph[fr].append(to)
self.graph[to].append(fr)
def goAndMark(self,start,visited):
visited[start-1] = True
for x in self.graph[start]:
if(visited[x-1] == False):
self.goAndMark(x,visited)
def solve(self,visited,n):
count = 0
for j in range(n):
if(visited[j]==False):
self.goAndMark(j+1,visited)
count+=1
return count
n = int(input())
List = [int(x) for x in input().split()]
G = Graph()
for i in range(n):
G.addEdge(i+1,List[i])
visited = [False] * n #0 based Indexing
print(G.solve(visited,n))
``` | output | 1 | 38,191 | 13 | 76,383 |
Provide tags and a correct Python 3 solution for this coding contest problem.
PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.
There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.
How many trees are there in the forest?
Input
The first line contains single integer n (1 ≤ n ≤ 104) — the number of Balls living in the forest.
The second line contains a sequence p1, p2, ..., pn of length n, where (1 ≤ pi ≤ n) holds and pi denotes the most distant from Ball i relative living on the same tree. If there are several most distant relatives living on the same tree, pi is the id of one with the smallest id.
It's guaranteed that the sequence p corresponds to some valid forest.
Hacking: To hack someone, you should provide a correct forest as a test. The sequence p will be calculated according to the forest and given to the solution you try to hack as input. Use the following format:
In the first line, output the integer n (1 ≤ n ≤ 104) — the number of Balls and the integer m (0 ≤ m < n) — the total number of edges in the forest. Then m lines should follow. The i-th of them should contain two integers ai and bi and represent an edge between vertices in which relatives ai and bi live. For example, the first sample is written as follows:
5 3
1 2
3 4
4 5
Output
You should output the number of trees in the forest where PolandBall lives.
Interaction
From the technical side, this problem is interactive. However, it should not affect you (except hacking) since there is no interaction.
Examples
Input
5
2 1 5 3 3
Output
2
Input
1
1
Output
1
Note
In the first sample testcase, possible forest is: 1-2 3-4-5.
There are 2 trees overall.
In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree. | instruction | 0 | 38,192 | 13 | 76,384 |
Tags: dfs and similar, dsu, graphs, interactive, trees
Correct Solution:
```
from collections import defaultdict
class Graph:
def __init__(self):
self.graph=defaultdict(list)
def addedge(self,u,v):
self.graph[u].append(v)
self.graph[v].append(u)
def dfs(self,s):
stack=[]
stack.append(s)
#print(self.visited)
while len(stack)!=0:
a=stack[-1]
#print(a,self.visited,s)
#print(stack)
stack.pop()
if(self.visited[a]==False):
#print(a)
self.visited[a]=True
for node in self.graph[a]:
if(self.visited[node]==False):
stack.append(node)
return
def dfsutill(self):
l=list(self.graph.keys())
self.visited=[False for i in range(len(l)+1)]
#print(self.visited)
#print(l)
c=0
for v in l:
if(self.visited[v]==False):
c+=1
self.dfs(v)
#print(self.visited)
return c
n=int(input())
l=list(map(int,input().split()))
g=Graph()
for i in range(1,n+1):
g.addedge(i,l[i-1])
print(g.dfsutill())
``` | output | 1 | 38,192 | 13 | 76,385 |
Provide tags and a correct Python 3 solution for this coding contest problem.
PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.
There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.
How many trees are there in the forest?
Input
The first line contains single integer n (1 ≤ n ≤ 104) — the number of Balls living in the forest.
The second line contains a sequence p1, p2, ..., pn of length n, where (1 ≤ pi ≤ n) holds and pi denotes the most distant from Ball i relative living on the same tree. If there are several most distant relatives living on the same tree, pi is the id of one with the smallest id.
It's guaranteed that the sequence p corresponds to some valid forest.
Hacking: To hack someone, you should provide a correct forest as a test. The sequence p will be calculated according to the forest and given to the solution you try to hack as input. Use the following format:
In the first line, output the integer n (1 ≤ n ≤ 104) — the number of Balls and the integer m (0 ≤ m < n) — the total number of edges in the forest. Then m lines should follow. The i-th of them should contain two integers ai and bi and represent an edge between vertices in which relatives ai and bi live. For example, the first sample is written as follows:
5 3
1 2
3 4
4 5
Output
You should output the number of trees in the forest where PolandBall lives.
Interaction
From the technical side, this problem is interactive. However, it should not affect you (except hacking) since there is no interaction.
Examples
Input
5
2 1 5 3 3
Output
2
Input
1
1
Output
1
Note
In the first sample testcase, possible forest is: 1-2 3-4-5.
There are 2 trees overall.
In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree. | instruction | 0 | 38,193 | 13 | 76,386 |
Tags: dfs and similar, dsu, graphs, interactive, trees
Correct Solution:
```
n = int(input())
v = [None] + [int(k) for k in input().split()]
p = [k for k in range(n + 1)]
ans = n
def anc(i):
if i == p[i]:
return p[i]
p[i] = anc(p[i])
return p[i]
def join(x, y):
global ans
px = anc(x)
py = anc(y)
if px != py:
p[px] = py
ans -= 1
for i in range(1, n + 1):
join(i, v[i])
print(ans)
``` | output | 1 | 38,193 | 13 | 76,387 |
Provide tags and a correct Python 3 solution for this coding contest problem.
PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.
There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.
How many trees are there in the forest?
Input
The first line contains single integer n (1 ≤ n ≤ 104) — the number of Balls living in the forest.
The second line contains a sequence p1, p2, ..., pn of length n, where (1 ≤ pi ≤ n) holds and pi denotes the most distant from Ball i relative living on the same tree. If there are several most distant relatives living on the same tree, pi is the id of one with the smallest id.
It's guaranteed that the sequence p corresponds to some valid forest.
Hacking: To hack someone, you should provide a correct forest as a test. The sequence p will be calculated according to the forest and given to the solution you try to hack as input. Use the following format:
In the first line, output the integer n (1 ≤ n ≤ 104) — the number of Balls and the integer m (0 ≤ m < n) — the total number of edges in the forest. Then m lines should follow. The i-th of them should contain two integers ai and bi and represent an edge between vertices in which relatives ai and bi live. For example, the first sample is written as follows:
5 3
1 2
3 4
4 5
Output
You should output the number of trees in the forest where PolandBall lives.
Interaction
From the technical side, this problem is interactive. However, it should not affect you (except hacking) since there is no interaction.
Examples
Input
5
2 1 5 3 3
Output
2
Input
1
1
Output
1
Note
In the first sample testcase, possible forest is: 1-2 3-4-5.
There are 2 trees overall.
In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree. | instruction | 0 | 38,194 | 13 | 76,388 |
Tags: dfs and similar, dsu, graphs, interactive, trees
Correct Solution:
```
visited = []
def dfs(adj,s):
visited[s] = True
for i in adj[s]:
if not visited[i]:
dfs(adj,i)
n = int(input())
a = list(map(int,input().split()))
adj = []
for i in range(n+5):
adj.append([])
visited.append(False)
for i in range(n):
adj[i+1].append(a[i])
adj[a[i]].append(i+1)
ans = 0
for i in range(1,n+1):
if not visited[i]:
ans += 1
dfs(adj,i)
print(ans)
``` | output | 1 | 38,194 | 13 | 76,389 |
Provide tags and a correct Python 3 solution for this coding contest problem.
PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.
There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.
How many trees are there in the forest?
Input
The first line contains single integer n (1 ≤ n ≤ 104) — the number of Balls living in the forest.
The second line contains a sequence p1, p2, ..., pn of length n, where (1 ≤ pi ≤ n) holds and pi denotes the most distant from Ball i relative living on the same tree. If there are several most distant relatives living on the same tree, pi is the id of one with the smallest id.
It's guaranteed that the sequence p corresponds to some valid forest.
Hacking: To hack someone, you should provide a correct forest as a test. The sequence p will be calculated according to the forest and given to the solution you try to hack as input. Use the following format:
In the first line, output the integer n (1 ≤ n ≤ 104) — the number of Balls and the integer m (0 ≤ m < n) — the total number of edges in the forest. Then m lines should follow. The i-th of them should contain two integers ai and bi and represent an edge between vertices in which relatives ai and bi live. For example, the first sample is written as follows:
5 3
1 2
3 4
4 5
Output
You should output the number of trees in the forest where PolandBall lives.
Interaction
From the technical side, this problem is interactive. However, it should not affect you (except hacking) since there is no interaction.
Examples
Input
5
2 1 5 3 3
Output
2
Input
1
1
Output
1
Note
In the first sample testcase, possible forest is: 1-2 3-4-5.
There are 2 trees overall.
In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree. | instruction | 0 | 38,195 | 13 | 76,390 |
Tags: dfs and similar, dsu, graphs, interactive, trees
Correct Solution:
```
n = int(input())
tree = list(range(n+1))
arr = list(map(int,input().split()))
def find(st):
if tree[st]!=st:
tree[st]= find(tree[st])
return tree[st]
for i in range(n):
tree[find(i+1)] = find(arr[i])
ans = 0
for i in range(1,n+1):
if find(i)==i:
ans+=1
print(ans)
``` | output | 1 | 38,195 | 13 | 76,391 |
Provide tags and a correct Python 3 solution for this coding contest problem.
PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.
There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.
How many trees are there in the forest?
Input
The first line contains single integer n (1 ≤ n ≤ 104) — the number of Balls living in the forest.
The second line contains a sequence p1, p2, ..., pn of length n, where (1 ≤ pi ≤ n) holds and pi denotes the most distant from Ball i relative living on the same tree. If there are several most distant relatives living on the same tree, pi is the id of one with the smallest id.
It's guaranteed that the sequence p corresponds to some valid forest.
Hacking: To hack someone, you should provide a correct forest as a test. The sequence p will be calculated according to the forest and given to the solution you try to hack as input. Use the following format:
In the first line, output the integer n (1 ≤ n ≤ 104) — the number of Balls and the integer m (0 ≤ m < n) — the total number of edges in the forest. Then m lines should follow. The i-th of them should contain two integers ai and bi and represent an edge between vertices in which relatives ai and bi live. For example, the first sample is written as follows:
5 3
1 2
3 4
4 5
Output
You should output the number of trees in the forest where PolandBall lives.
Interaction
From the technical side, this problem is interactive. However, it should not affect you (except hacking) since there is no interaction.
Examples
Input
5
2 1 5 3 3
Output
2
Input
1
1
Output
1
Note
In the first sample testcase, possible forest is: 1-2 3-4-5.
There are 2 trees overall.
In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree. | instruction | 0 | 38,196 | 13 | 76,392 |
Tags: dfs and similar, dsu, graphs, interactive, trees
Correct Solution:
```
#!/usr/bin/python3
n = int(input())
p = list(map(int, input().split()))
for i in range(n):
p[i] -= 1
ans = 0
for i in range(n):
if p[i] == i:
ans += 2
elif p[p[i]] == i:
ans += 1
print(ans // 2)
print(ans, file=__import__("sys").stderr)
``` | output | 1 | 38,196 | 13 | 76,393 |
Provide tags and a correct Python 3 solution for this coding contest problem.
PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.
There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.
How many trees are there in the forest?
Input
The first line contains single integer n (1 ≤ n ≤ 104) — the number of Balls living in the forest.
The second line contains a sequence p1, p2, ..., pn of length n, where (1 ≤ pi ≤ n) holds and pi denotes the most distant from Ball i relative living on the same tree. If there are several most distant relatives living on the same tree, pi is the id of one with the smallest id.
It's guaranteed that the sequence p corresponds to some valid forest.
Hacking: To hack someone, you should provide a correct forest as a test. The sequence p will be calculated according to the forest and given to the solution you try to hack as input. Use the following format:
In the first line, output the integer n (1 ≤ n ≤ 104) — the number of Balls and the integer m (0 ≤ m < n) — the total number of edges in the forest. Then m lines should follow. The i-th of them should contain two integers ai and bi and represent an edge between vertices in which relatives ai and bi live. For example, the first sample is written as follows:
5 3
1 2
3 4
4 5
Output
You should output the number of trees in the forest where PolandBall lives.
Interaction
From the technical side, this problem is interactive. However, it should not affect you (except hacking) since there is no interaction.
Examples
Input
5
2 1 5 3 3
Output
2
Input
1
1
Output
1
Note
In the first sample testcase, possible forest is: 1-2 3-4-5.
There are 2 trees overall.
In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree. | instruction | 0 | 38,197 | 13 | 76,394 |
Tags: dfs and similar, dsu, graphs, interactive, trees
Correct Solution:
```
def main():
MAXN = int(1e4 + 7)
par = []
for i in range(MAXN):
par.append(i)
def find(i):
if i == par[i]:
return i
return find(par[i])
def union(i, j):
p = find(i)
q = find(j)
if p == q:
return
par[p] = q
n = int(input())
p = list(map(int, input().split(' ')))
for i in range(n):
union(i, p[i] - 1)
s = set()
for i in range(n):
s.add(find(i))
print(len(s))
main()
``` | output | 1 | 38,197 | 13 | 76,395 |
Provide tags and a correct Python 3 solution for this coding contest problem.
PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.
There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.
How many trees are there in the forest?
Input
The first line contains single integer n (1 ≤ n ≤ 104) — the number of Balls living in the forest.
The second line contains a sequence p1, p2, ..., pn of length n, where (1 ≤ pi ≤ n) holds and pi denotes the most distant from Ball i relative living on the same tree. If there are several most distant relatives living on the same tree, pi is the id of one with the smallest id.
It's guaranteed that the sequence p corresponds to some valid forest.
Hacking: To hack someone, you should provide a correct forest as a test. The sequence p will be calculated according to the forest and given to the solution you try to hack as input. Use the following format:
In the first line, output the integer n (1 ≤ n ≤ 104) — the number of Balls and the integer m (0 ≤ m < n) — the total number of edges in the forest. Then m lines should follow. The i-th of them should contain two integers ai and bi and represent an edge between vertices in which relatives ai and bi live. For example, the first sample is written as follows:
5 3
1 2
3 4
4 5
Output
You should output the number of trees in the forest where PolandBall lives.
Interaction
From the technical side, this problem is interactive. However, it should not affect you (except hacking) since there is no interaction.
Examples
Input
5
2 1 5 3 3
Output
2
Input
1
1
Output
1
Note
In the first sample testcase, possible forest is: 1-2 3-4-5.
There are 2 trees overall.
In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree. | instruction | 0 | 38,198 | 13 | 76,396 |
Tags: dfs and similar, dsu, graphs, interactive, trees
Correct Solution:
```
#https://codeforces.com/problemset/problem/755/C
import sys
import math
try:
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
except:
pass
class DisjointSet():
def __init__(self,n):
self.parent=[0]
for i in range(1,n+1):
self.parent.append(i)
def find(self,node):
if(node!=self.parent[node]):
self.parent[node]=self.find(self.parent[node])
return self.parent[node]
def union(self,u,v):
leader_u=self.find(u)
leader_v=self.find(v)
if(leader_u!=leader_v):
self.parent[leader_u]=leader_v
n=int(input())
relatives=[int(x) for x in input().split()]
ds=DisjointSet(n)
edge_index=[i for i in range(n+1)]
for i,r in enumerate(relatives):
#print(edge_index[i+1],r)
ds.union(edge_index[i+1],r)
trees=0
seen=set()
for i in range(1,n+1):
leader=ds.find(i)
if(leader not in seen):
seen.add(leader)
trees+=1
print(trees)
``` | output | 1 | 38,198 | 13 | 76,397 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.
There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.
How many trees are there in the forest?
Input
The first line contains single integer n (1 ≤ n ≤ 104) — the number of Balls living in the forest.
The second line contains a sequence p1, p2, ..., pn of length n, where (1 ≤ pi ≤ n) holds and pi denotes the most distant from Ball i relative living on the same tree. If there are several most distant relatives living on the same tree, pi is the id of one with the smallest id.
It's guaranteed that the sequence p corresponds to some valid forest.
Hacking: To hack someone, you should provide a correct forest as a test. The sequence p will be calculated according to the forest and given to the solution you try to hack as input. Use the following format:
In the first line, output the integer n (1 ≤ n ≤ 104) — the number of Balls and the integer m (0 ≤ m < n) — the total number of edges in the forest. Then m lines should follow. The i-th of them should contain two integers ai and bi and represent an edge between vertices in which relatives ai and bi live. For example, the first sample is written as follows:
5 3
1 2
3 4
4 5
Output
You should output the number of trees in the forest where PolandBall lives.
Interaction
From the technical side, this problem is interactive. However, it should not affect you (except hacking) since there is no interaction.
Examples
Input
5
2 1 5 3 3
Output
2
Input
1
1
Output
1
Note
In the first sample testcase, possible forest is: 1-2 3-4-5.
There are 2 trees overall.
In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree.
Submitted Solution:
```
n=int(input())
l=list(map(int,input().split()))
p=list(range(n+1))
h=[0]*(n+1)
def pred(x):
if x!=p[x]: p[x]=pred(p[x]);
return p[x]
def union(a,b):
a,b=pred(a),pred(b)
if h[a]<h[b]: a,b=b,a
p[b]=a
if h[a]==h[b]: h[a]+=1
for i in range(1,n+1):
union(i,l[i-1])
for i in range(n+1):
pred(i)
le=len(set(p))
print(le-1)
``` | instruction | 0 | 38,199 | 13 | 76,398 |
Yes | output | 1 | 38,199 | 13 | 76,399 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.
There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.
How many trees are there in the forest?
Input
The first line contains single integer n (1 ≤ n ≤ 104) — the number of Balls living in the forest.
The second line contains a sequence p1, p2, ..., pn of length n, where (1 ≤ pi ≤ n) holds and pi denotes the most distant from Ball i relative living on the same tree. If there are several most distant relatives living on the same tree, pi is the id of one with the smallest id.
It's guaranteed that the sequence p corresponds to some valid forest.
Hacking: To hack someone, you should provide a correct forest as a test. The sequence p will be calculated according to the forest and given to the solution you try to hack as input. Use the following format:
In the first line, output the integer n (1 ≤ n ≤ 104) — the number of Balls and the integer m (0 ≤ m < n) — the total number of edges in the forest. Then m lines should follow. The i-th of them should contain two integers ai and bi and represent an edge between vertices in which relatives ai and bi live. For example, the first sample is written as follows:
5 3
1 2
3 4
4 5
Output
You should output the number of trees in the forest where PolandBall lives.
Interaction
From the technical side, this problem is interactive. However, it should not affect you (except hacking) since there is no interaction.
Examples
Input
5
2 1 5 3 3
Output
2
Input
1
1
Output
1
Note
In the first sample testcase, possible forest is: 1-2 3-4-5.
There are 2 trees overall.
In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree.
Submitted Solution:
```
def find(a,x):
while(1):
if(a[x]<0):
return x
else:
x=a[x]
n=int(input())
a=[-1]*(n+1)
ed=[0]+[int(y) for y in input().split(' ')]
for i in range(1,1+n):
p1=find(a,i)
p2=find(a,ed[i])
# print(p1,p2,"for child ",i,a)
if p1!=p2:
a[p1]+=a[p2]
a[p2]=p1
c=0
#print(a)
for j in range(1,1+n):
if a[j]<0:
c=c+1
print(c)
``` | instruction | 0 | 38,200 | 13 | 76,400 |
Yes | output | 1 | 38,200 | 13 | 76,401 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.
There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.
How many trees are there in the forest?
Input
The first line contains single integer n (1 ≤ n ≤ 104) — the number of Balls living in the forest.
The second line contains a sequence p1, p2, ..., pn of length n, where (1 ≤ pi ≤ n) holds and pi denotes the most distant from Ball i relative living on the same tree. If there are several most distant relatives living on the same tree, pi is the id of one with the smallest id.
It's guaranteed that the sequence p corresponds to some valid forest.
Hacking: To hack someone, you should provide a correct forest as a test. The sequence p will be calculated according to the forest and given to the solution you try to hack as input. Use the following format:
In the first line, output the integer n (1 ≤ n ≤ 104) — the number of Balls and the integer m (0 ≤ m < n) — the total number of edges in the forest. Then m lines should follow. The i-th of them should contain two integers ai and bi and represent an edge between vertices in which relatives ai and bi live. For example, the first sample is written as follows:
5 3
1 2
3 4
4 5
Output
You should output the number of trees in the forest where PolandBall lives.
Interaction
From the technical side, this problem is interactive. However, it should not affect you (except hacking) since there is no interaction.
Examples
Input
5
2 1 5 3 3
Output
2
Input
1
1
Output
1
Note
In the first sample testcase, possible forest is: 1-2 3-4-5.
There are 2 trees overall.
In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree.
Submitted Solution:
```
def main():
n = int(input())
p = [int(c) - 1 for c in input().split()]
links = [None] * n
pairs = list(enumerate(p))
pairs.sort(key=lambda x: x[1])
curr = 0
for i, e in pairs:
if links[e] is None:
links[e] = curr
curr += 1
links[i] = links[e]
print(curr)
if __name__ == '__main__':
main()
``` | instruction | 0 | 38,201 | 13 | 76,402 |
Yes | output | 1 | 38,201 | 13 | 76,403 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.
There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.
How many trees are there in the forest?
Input
The first line contains single integer n (1 ≤ n ≤ 104) — the number of Balls living in the forest.
The second line contains a sequence p1, p2, ..., pn of length n, where (1 ≤ pi ≤ n) holds and pi denotes the most distant from Ball i relative living on the same tree. If there are several most distant relatives living on the same tree, pi is the id of one with the smallest id.
It's guaranteed that the sequence p corresponds to some valid forest.
Hacking: To hack someone, you should provide a correct forest as a test. The sequence p will be calculated according to the forest and given to the solution you try to hack as input. Use the following format:
In the first line, output the integer n (1 ≤ n ≤ 104) — the number of Balls and the integer m (0 ≤ m < n) — the total number of edges in the forest. Then m lines should follow. The i-th of them should contain two integers ai and bi and represent an edge between vertices in which relatives ai and bi live. For example, the first sample is written as follows:
5 3
1 2
3 4
4 5
Output
You should output the number of trees in the forest where PolandBall lives.
Interaction
From the technical side, this problem is interactive. However, it should not affect you (except hacking) since there is no interaction.
Examples
Input
5
2 1 5 3 3
Output
2
Input
1
1
Output
1
Note
In the first sample testcase, possible forest is: 1-2 3-4-5.
There are 2 trees overall.
In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree.
Submitted Solution:
```
class DisjointSet:
def __init__(self,N):
self._N = N
self._rank = N*[0]
self._parent = list(range(N))
def find(self, i):
if self._parent[i] != i:
self._parent[i] = self.find(self._parent[i])
return self._parent[i]
def union(self,x,y):
px = self.find(x)
py = self.find(y)
if self._rank[px] < self._rank[py]:
self._parent[px] = py
else:
if self._rank[px] == self._rank[py]:
self._rank[px] += 1
self._parent[py] = px
if __name__ == "__main__":
N = int(input())
nbrs = list(map(int, input().strip().split()))
for i in range(N):
nbrs[i] -= 1
cc = DisjointSet(N)
for i in range(N):
cc.union(i,nbrs[i])
result=set([cc.find(i) for i in range(N)])
print(len(result))
``` | instruction | 0 | 38,202 | 13 | 76,404 |
Yes | output | 1 | 38,202 | 13 | 76,405 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.
There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.
How many trees are there in the forest?
Input
The first line contains single integer n (1 ≤ n ≤ 104) — the number of Balls living in the forest.
The second line contains a sequence p1, p2, ..., pn of length n, where (1 ≤ pi ≤ n) holds and pi denotes the most distant from Ball i relative living on the same tree. If there are several most distant relatives living on the same tree, pi is the id of one with the smallest id.
It's guaranteed that the sequence p corresponds to some valid forest.
Hacking: To hack someone, you should provide a correct forest as a test. The sequence p will be calculated according to the forest and given to the solution you try to hack as input. Use the following format:
In the first line, output the integer n (1 ≤ n ≤ 104) — the number of Balls and the integer m (0 ≤ m < n) — the total number of edges in the forest. Then m lines should follow. The i-th of them should contain two integers ai and bi and represent an edge between vertices in which relatives ai and bi live. For example, the first sample is written as follows:
5 3
1 2
3 4
4 5
Output
You should output the number of trees in the forest where PolandBall lives.
Interaction
From the technical side, this problem is interactive. However, it should not affect you (except hacking) since there is no interaction.
Examples
Input
5
2 1 5 3 3
Output
2
Input
1
1
Output
1
Note
In the first sample testcase, possible forest is: 1-2 3-4-5.
There are 2 trees overall.
In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree.
Submitted Solution:
```
import sys
noh = int(sys.stdin.readline())
tree = 0
loca = list(map(int, sys.stdin.readline().split()))
ap = {}
for i in range(noh):
if loca[i] not in ap:
tree += 1
ap[i+1] = tree
ap[loca[i]] = tree
print(tree)
``` | instruction | 0 | 38,203 | 13 | 76,406 |
No | output | 1 | 38,203 | 13 | 76,407 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.
There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.
How many trees are there in the forest?
Input
The first line contains single integer n (1 ≤ n ≤ 104) — the number of Balls living in the forest.
The second line contains a sequence p1, p2, ..., pn of length n, where (1 ≤ pi ≤ n) holds and pi denotes the most distant from Ball i relative living on the same tree. If there are several most distant relatives living on the same tree, pi is the id of one with the smallest id.
It's guaranteed that the sequence p corresponds to some valid forest.
Hacking: To hack someone, you should provide a correct forest as a test. The sequence p will be calculated according to the forest and given to the solution you try to hack as input. Use the following format:
In the first line, output the integer n (1 ≤ n ≤ 104) — the number of Balls and the integer m (0 ≤ m < n) — the total number of edges in the forest. Then m lines should follow. The i-th of them should contain two integers ai and bi and represent an edge between vertices in which relatives ai and bi live. For example, the first sample is written as follows:
5 3
1 2
3 4
4 5
Output
You should output the number of trees in the forest where PolandBall lives.
Interaction
From the technical side, this problem is interactive. However, it should not affect you (except hacking) since there is no interaction.
Examples
Input
5
2 1 5 3 3
Output
2
Input
1
1
Output
1
Note
In the first sample testcase, possible forest is: 1-2 3-4-5.
There are 2 trees overall.
In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree.
Submitted Solution:
```
n = int(input())
balls = list(map(int, input().split()))
lonely = 0
forest = list()
for i in range(n):
if i+1 == balls[i]:
lonely += 1
else:
new = {i+1, balls[i]}
for t in range(len(forest)):
if i+1 in forest[t] or balls[i] in forest[t]:
forest[t].update(new)
break
else:
forest.append(new)
print(lonely+len(forest))
``` | instruction | 0 | 38,204 | 13 | 76,408 |
No | output | 1 | 38,204 | 13 | 76,409 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.
There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.
How many trees are there in the forest?
Input
The first line contains single integer n (1 ≤ n ≤ 104) — the number of Balls living in the forest.
The second line contains a sequence p1, p2, ..., pn of length n, where (1 ≤ pi ≤ n) holds and pi denotes the most distant from Ball i relative living on the same tree. If there are several most distant relatives living on the same tree, pi is the id of one with the smallest id.
It's guaranteed that the sequence p corresponds to some valid forest.
Hacking: To hack someone, you should provide a correct forest as a test. The sequence p will be calculated according to the forest and given to the solution you try to hack as input. Use the following format:
In the first line, output the integer n (1 ≤ n ≤ 104) — the number of Balls and the integer m (0 ≤ m < n) — the total number of edges in the forest. Then m lines should follow. The i-th of them should contain two integers ai and bi and represent an edge between vertices in which relatives ai and bi live. For example, the first sample is written as follows:
5 3
1 2
3 4
4 5
Output
You should output the number of trees in the forest where PolandBall lives.
Interaction
From the technical side, this problem is interactive. However, it should not affect you (except hacking) since there is no interaction.
Examples
Input
5
2 1 5 3 3
Output
2
Input
1
1
Output
1
Note
In the first sample testcase, possible forest is: 1-2 3-4-5.
There are 2 trees overall.
In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree.
Submitted Solution:
```
import collections
class Solution:
def solve(self, seq):
self.graph = collections.defaultdict(list)
for i, item in enumerate(seq, 1):
idMin = min(i, item)
idMax = max(i, item)
self.graph[idMin].append(idMax)
# print(self.graph)
ans = 0
for item, childSet in self.graph.items():
if len(childSet) > 0:
ans += 1
return ans
sol = Solution()
n = int(input().strip())
seq = list(map(int, input().strip().split()))
print(sol.solve(seq))
``` | instruction | 0 | 38,205 | 13 | 76,410 |
No | output | 1 | 38,205 | 13 | 76,411 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.
There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.
How many trees are there in the forest?
Input
The first line contains single integer n (1 ≤ n ≤ 104) — the number of Balls living in the forest.
The second line contains a sequence p1, p2, ..., pn of length n, where (1 ≤ pi ≤ n) holds and pi denotes the most distant from Ball i relative living on the same tree. If there are several most distant relatives living on the same tree, pi is the id of one with the smallest id.
It's guaranteed that the sequence p corresponds to some valid forest.
Hacking: To hack someone, you should provide a correct forest as a test. The sequence p will be calculated according to the forest and given to the solution you try to hack as input. Use the following format:
In the first line, output the integer n (1 ≤ n ≤ 104) — the number of Balls and the integer m (0 ≤ m < n) — the total number of edges in the forest. Then m lines should follow. The i-th of them should contain two integers ai and bi and represent an edge between vertices in which relatives ai and bi live. For example, the first sample is written as follows:
5 3
1 2
3 4
4 5
Output
You should output the number of trees in the forest where PolandBall lives.
Interaction
From the technical side, this problem is interactive. However, it should not affect you (except hacking) since there is no interaction.
Examples
Input
5
2 1 5 3 3
Output
2
Input
1
1
Output
1
Note
In the first sample testcase, possible forest is: 1-2 3-4-5.
There are 2 trees overall.
In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree.
Submitted Solution:
```
n = int(input())
p = list(map(int, input().split()))
counter = 0
for i in range(n):
if p[i] == i + 1:
counter += 1
dividend = (len(set(p)) - counter)
divisor = 2 + (len(set(p)) - counter) % 2 + counter
print(dividend // divisor)
``` | instruction | 0 | 38,206 | 13 | 76,412 |
No | output | 1 | 38,206 | 13 | 76,413 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a [directed graph](https://en.wikipedia.org/wiki/Directed_graph) consisting of n vertices and m edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it.
Can you make this graph [acyclic](https://en.wikipedia.org/wiki/Directed_acyclic_graph) by removing at most one edge from it? A directed graph is called acyclic iff it doesn't contain any cycle (a non-empty path that starts and ends in the same vertex).
Input
The first line contains two integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ min(n(n - 1), 100000)) — the number of vertices and the number of edges, respectively.
Then m lines follow. Each line contains two integers u and v denoting a directed edge going from vertex u to vertex v (1 ≤ u, v ≤ n, u ≠ v). Each ordered pair (u, v) is listed at most once (there is at most one directed edge from u to v).
Output
If it is possible to make this graph acyclic by removing at most one edge, print YES. Otherwise, print NO.
Examples
Input
3 4
1 2
2 3
3 2
3 1
Output
YES
Input
5 6
1 2
2 3
3 2
3 1
2 1
4 5
Output
NO
Note
In the first example you can remove edge <image>, and the graph becomes acyclic.
In the second example you have to remove at least two edges (for example, <image> and <image>) in order to make the graph acyclic. | instruction | 0 | 38,289 | 13 | 76,578 |
Tags: dfs and similar, graphs
Correct Solution:
```
import sys
input = sys.stdin.readline
def get_input():
n, m = [int(x) for x in input().split(' ')]
digraph = [[] for _ in range(n + 1)]
for _ in range(m):
c1, c2 = [int(x) for x in input().split(' ')]
digraph[c1].append(c2)
return digraph
def dfs(graph, u=-1, v=-1):
n = len(graph)
pi = [None] * n
color = ['white'] * n
for node in range(1, n):
if color[node] == 'white':
cicle = dfs_visit(graph, node, color, pi, u, v)
if cicle is not None:
return cicle
return None
def dfs_visit(graph, root, color, pi, u, v):
stack = [root]
while stack:
current_node = stack[-1]
if color[current_node] != 'white':
stack.pop()
color[current_node] = 'black'
continue
color[current_node] = 'grey'
for adj in graph[current_node]:
if (current_node, adj) == (u, v):
continue
if color[adj] == 'white':
pi[adj] = current_node
stack.append(adj)
elif color[adj] == 'grey':
cicle = [adj]
while current_node != adj:
cicle.append(current_node)
current_node = pi[current_node]
cicle.append(adj)
return cicle
return None
if __name__ == "__main__":
digraph = get_input()
cicle = dfs(digraph)
if cicle is None:
print("YES")
else:
cicle.reverse()
for i in range(len(cicle) - 1):
c = dfs(digraph, cicle[i], cicle[i + 1])
if c is None:
print("YES")
break
else:
print("NO")
``` | output | 1 | 38,289 | 13 | 76,579 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a [directed graph](https://en.wikipedia.org/wiki/Directed_graph) consisting of n vertices and m edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it.
Can you make this graph [acyclic](https://en.wikipedia.org/wiki/Directed_acyclic_graph) by removing at most one edge from it? A directed graph is called acyclic iff it doesn't contain any cycle (a non-empty path that starts and ends in the same vertex).
Input
The first line contains two integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ min(n(n - 1), 100000)) — the number of vertices and the number of edges, respectively.
Then m lines follow. Each line contains two integers u and v denoting a directed edge going from vertex u to vertex v (1 ≤ u, v ≤ n, u ≠ v). Each ordered pair (u, v) is listed at most once (there is at most one directed edge from u to v).
Output
If it is possible to make this graph acyclic by removing at most one edge, print YES. Otherwise, print NO.
Examples
Input
3 4
1 2
2 3
3 2
3 1
Output
YES
Input
5 6
1 2
2 3
3 2
3 1
2 1
4 5
Output
NO
Note
In the first example you can remove edge <image>, and the graph becomes acyclic.
In the second example you have to remove at least two edges (for example, <image> and <image>) in order to make the graph acyclic. | instruction | 0 | 38,290 | 13 | 76,580 |
Tags: dfs and similar, graphs
Correct Solution:
```
import sys
def prepare():
stack = [i for i in range(n) if deg[i] == 0]
cnt = 0
while stack:
v = stack.pop()
cnt += 1
for dest in adj[v]:
deg[dest] -= 1
if deg[dest] == 0:
stack.append(dest)
adj[v].clear()
return cnt == n
def solve(st):
stack = [st]
visited = [0]*n
cnt = 0
while stack:
v = stack.pop()
cnt += 1
for dest in adj[v]:
if dest == st:
continue
visited[dest] += 1
if deg[dest] == visited[dest]:
stack.append(dest)
return cnt == m
n, m = map(int, sys.stdin.buffer.readline().decode('utf-8').split())
adj = [[] for _ in range(n)]
rev = [[] for _ in range(n)]
deg = [0]*n
for u, v in (map(int, line.decode('utf-8').split()) for line in sys.stdin.buffer):
adj[u-1].append(v-1)
rev[v-1].append(u-1)
deg[v-1] += 1
ok = prepare()
if ok:
print('YES')
exit()
m = len([1 for i in range(n) if deg[i] > 0])
for i in range(n):
if deg[i] == 1 and solve(i):
print('YES')
exit()
print('NO')
``` | output | 1 | 38,290 | 13 | 76,581 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a [directed graph](https://en.wikipedia.org/wiki/Directed_graph) consisting of n vertices and m edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it.
Can you make this graph [acyclic](https://en.wikipedia.org/wiki/Directed_acyclic_graph) by removing at most one edge from it? A directed graph is called acyclic iff it doesn't contain any cycle (a non-empty path that starts and ends in the same vertex).
Input
The first line contains two integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ min(n(n - 1), 100000)) — the number of vertices and the number of edges, respectively.
Then m lines follow. Each line contains two integers u and v denoting a directed edge going from vertex u to vertex v (1 ≤ u, v ≤ n, u ≠ v). Each ordered pair (u, v) is listed at most once (there is at most one directed edge from u to v).
Output
If it is possible to make this graph acyclic by removing at most one edge, print YES. Otherwise, print NO.
Examples
Input
3 4
1 2
2 3
3 2
3 1
Output
YES
Input
5 6
1 2
2 3
3 2
3 1
2 1
4 5
Output
NO
Note
In the first example you can remove edge <image>, and the graph becomes acyclic.
In the second example you have to remove at least two edges (for example, <image> and <image>) in order to make the graph acyclic. | instruction | 0 | 38,291 | 13 | 76,582 |
Tags: dfs and similar, graphs
Correct Solution:
```
def dfs(g, u, visited, call_stack):
visited[u] = True
call_stack.add(u)
for v in g[u]:
if v in call_stack:
return [u, v]
if not visited[v]:
d = dfs(g, v, visited, call_stack)
call_stack.discard(v)
if d is not None:
return [u] + d
return None
def find_cycle(g, n):
visited = [False] * n
d = None
for i in range(n):
if not visited[i]:
call_stack = set()
d = dfs(g, i, visited, call_stack)
if d is not None:
break
return d
if __name__ == '__main__':
n, m = map(int, input().split())
g = []
for _ in range(n):
g.append([])
for _ in range(m):
u, v = map(int, input().split())
g[u-1].append(v-1)
out = False
c = find_cycle(g, n)
if c:
first_index = c.index(c[-1])
c = c[first_index:]
for i in range(len(c)-1):
if i != 0:
g[c[i-1]].append(c[i])
g[c[i]].remove(c[i+1])
out = out or find_cycle(g, n) is None
else:
out = True
print('YES' if out else 'NO')
``` | output | 1 | 38,291 | 13 | 76,583 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a [directed graph](https://en.wikipedia.org/wiki/Directed_graph) consisting of n vertices and m edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it.
Can you make this graph [acyclic](https://en.wikipedia.org/wiki/Directed_acyclic_graph) by removing at most one edge from it? A directed graph is called acyclic iff it doesn't contain any cycle (a non-empty path that starts and ends in the same vertex).
Input
The first line contains two integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ min(n(n - 1), 100000)) — the number of vertices and the number of edges, respectively.
Then m lines follow. Each line contains two integers u and v denoting a directed edge going from vertex u to vertex v (1 ≤ u, v ≤ n, u ≠ v). Each ordered pair (u, v) is listed at most once (there is at most one directed edge from u to v).
Output
If it is possible to make this graph acyclic by removing at most one edge, print YES. Otherwise, print NO.
Examples
Input
3 4
1 2
2 3
3 2
3 1
Output
YES
Input
5 6
1 2
2 3
3 2
3 1
2 1
4 5
Output
NO
Note
In the first example you can remove edge <image>, and the graph becomes acyclic.
In the second example you have to remove at least two edges (for example, <image> and <image>) in order to make the graph acyclic. | instruction | 0 | 38,292 | 13 | 76,584 |
Tags: dfs and similar, graphs
Correct Solution:
```
have = False
cycle_begin, block_u, block_v = -1, -1, -1
g, mark, cycle = [], [], []
def dfs(u):
global have, cycle_begin
mark[u] = 1
for v in g[u]:
if u == block_u and v == block_v:
continue
if mark[v] == 0:
if dfs(v):
if have:
cycle.append(u)
if u == cycle_begin:
have = False
return True
elif mark[v] == 1:
have = True
cycle_begin = v
cycle.append(u)
return True
mark[u] = 2
return False
n, m = map(int, input().split())
g = [[] for _ in range(n)]
mark = [0 for _ in range(n)]
for _ in range(m):
u, v = map(int, input().split())
u -= 1
v -= 1
g[u].append(v)
for i in range(n):
if mark[i] == 0 and dfs(i):
break
if cycle_begin == -1:
print("YES")
else:
cycle.append(cycle[0])
for u in range(len(cycle) - 1, 0, -1):
block_u = cycle[u]
block_v = cycle[u - 1]
mark = [0 for _ in range(n)]
ok = True
for u in range(n):
if mark[u] == 0 and dfs(u):
ok = False
break
if ok:
print("YES")
exit()
print("NO")
``` | output | 1 | 38,292 | 13 | 76,585 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a [directed graph](https://en.wikipedia.org/wiki/Directed_graph) consisting of n vertices and m edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it.
Can you make this graph [acyclic](https://en.wikipedia.org/wiki/Directed_acyclic_graph) by removing at most one edge from it? A directed graph is called acyclic iff it doesn't contain any cycle (a non-empty path that starts and ends in the same vertex).
Input
The first line contains two integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ min(n(n - 1), 100000)) — the number of vertices and the number of edges, respectively.
Then m lines follow. Each line contains two integers u and v denoting a directed edge going from vertex u to vertex v (1 ≤ u, v ≤ n, u ≠ v). Each ordered pair (u, v) is listed at most once (there is at most one directed edge from u to v).
Output
If it is possible to make this graph acyclic by removing at most one edge, print YES. Otherwise, print NO.
Examples
Input
3 4
1 2
2 3
3 2
3 1
Output
YES
Input
5 6
1 2
2 3
3 2
3 1
2 1
4 5
Output
NO
Note
In the first example you can remove edge <image>, and the graph becomes acyclic.
In the second example you have to remove at least two edges (for example, <image> and <image>) in order to make the graph acyclic. | instruction | 0 | 38,293 | 13 | 76,586 |
Tags: dfs and similar, graphs
Correct Solution:
```
n, m = [int(x) for x in input().split()]
a = [[] for i in range(n)]
for i in range(m):
u, v = [int(x) for x in input().split()]
a[u - 1].append(v - 1)
color = [0] * n # 0 - white, 1 - grey, 2 - black
cycle = []
blocked_u, blocked_v = -1, -1
def dfs(u):
global color
global cycle
if color[u]:
return
color[u] = 1
for v in a[u]:
if u == blocked_u and v == blocked_v:
continue
if color[v] == 0:
dfs(v)
if color[v] == 1 or cycle:
if not(cycle):
cycle.append(v)
cycle.append(u)
return True
color[u] = 2
return False
def find_cycle():
global color
global cycle
color = [0] * n # 0 - white, 1 - grey, 2 - black
cycle = []
for u in range(n):
if dfs(u):
break
result = cycle[::-1]
return {(result[i], result[(i + 1) % len(result)]) for i in range(len(result))}
cur = find_cycle()
if not(cur):
print('YES')
exit()
for bu, bv in cur:
blocked_u = bu
blocked_v = bv
new = find_cycle()
if not(new):
print('YES')
exit()
print('NO')
``` | output | 1 | 38,293 | 13 | 76,587 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a [directed graph](https://en.wikipedia.org/wiki/Directed_graph) consisting of n vertices and m edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it.
Can you make this graph [acyclic](https://en.wikipedia.org/wiki/Directed_acyclic_graph) by removing at most one edge from it? A directed graph is called acyclic iff it doesn't contain any cycle (a non-empty path that starts and ends in the same vertex).
Input
The first line contains two integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ min(n(n - 1), 100000)) — the number of vertices and the number of edges, respectively.
Then m lines follow. Each line contains two integers u and v denoting a directed edge going from vertex u to vertex v (1 ≤ u, v ≤ n, u ≠ v). Each ordered pair (u, v) is listed at most once (there is at most one directed edge from u to v).
Output
If it is possible to make this graph acyclic by removing at most one edge, print YES. Otherwise, print NO.
Examples
Input
3 4
1 2
2 3
3 2
3 1
Output
YES
Input
5 6
1 2
2 3
3 2
3 1
2 1
4 5
Output
NO
Note
In the first example you can remove edge <image>, and the graph becomes acyclic.
In the second example you have to remove at least two edges (for example, <image> and <image>) in order to make the graph acyclic. | instruction | 0 | 38,294 | 13 | 76,588 |
Tags: dfs and similar, graphs
Correct Solution:
```
cycle_begin, block_u, block_v = -1, -1, -1
g, mark, prev, cycle = [], [], [], []
def dfs(u):
global cycle_begin
mark[u] = 1
for v in g[u]:
if u == block_u and v == block_v:
continue
if mark[v] == 0:
prev[v] = u
if dfs(v):
return True
elif mark[v] == 1:
prev[v] = u
cycle_begin = u
return True
mark[u] = 2
return False
n, m = map(int, input().split())
g = [[] for _ in range(n)]
mark = [0 for _ in range(n)]
prev = [0 for _ in range(n)]
for _ in range(m):
u, v = map(int, input().split())
u -= 1
v -= 1
g[u].append(v)
for i in range(n):
if mark[i] == 0 and dfs(i):
break
if cycle_begin == -1:
print("YES")
else:
u = cycle_begin
while u != cycle_begin or len(cycle) == 0:
cycle.append(u)
u = prev[u]
cycle.append(cycle_begin)
for u in range(len(cycle) - 1, 0, -1):
block_u = cycle[u]
block_v = cycle[u - 1]
mark = [0 for _ in range(n)]
have = False
for u in range(n):
if mark[u] == 0 and dfs(u):
have = True
break
if not have:
print("YES")
exit()
print("NO")
``` | output | 1 | 38,294 | 13 | 76,589 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.