message stringlengths 2 49.9k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 446 108k | cluster float64 13 13 | __index_level_0__ int64 892 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Boboniu has a directed graph with n vertices and m edges.
The out-degree of each vertex is at most k.
Each edge has an integer weight between 1 and m. No two edges have equal weights.
Boboniu likes to walk on the graph with some specific rules, which is represented by a tuple (c_1,c_2,…,c_k). If he now stands on a vertex u with out-degree i, then he will go to the next vertex by the edge with the c_i-th (1≤ c_i≤ i) smallest weight among all edges outgoing from u.
Now Boboniu asks you to calculate the number of tuples (c_1,c_2,…,c_k) such that
* 1≤ c_i≤ i for all i (1≤ i≤ k).
* Starting from any vertex u, it is possible to go back to u in finite time by walking on the graph under the described rules.
Input
The first line contains three integers n, m and k (2≤ n≤ 2⋅ 10^5, 2≤ m≤ min(2⋅ 10^5,n(n-1) ), 1≤ k≤ 9).
Each of the next m lines contains three integers u, v and w (1≤ u,v≤ n,u≠ v,1≤ w≤ m), denoting an edge from u to v with weight w. It is guaranteed that there are no self-loops or multiple edges and each vertex has at least one edge starting from itself.
It is guaranteed that the out-degree of each vertex is at most k and no two edges have equal weight.
Output
Print one integer: the number of tuples.
Examples
Input
4 6 3
4 2 1
1 2 2
2 4 3
4 1 4
4 3 5
3 1 6
Output
2
Input
5 5 1
1 4 1
5 1 2
2 5 3
4 3 4
3 2 5
Output
1
Input
6 13 4
3 5 1
2 5 2
6 3 3
1 4 4
2 6 5
5 3 6
4 1 7
4 3 8
5 2 9
4 2 10
2 1 11
6 1 12
4 6 13
Output
1
Note
For the first example, there are two tuples: (1,1,3) and (1,2,3). The blue edges in the picture denote the c_i-th smallest edges for each vertex, which Boboniu chooses to go through.
<image>
For the third example, there's only one tuple: (1,2,2,2).
<image>
The out-degree of vertex u means the number of edges outgoing from u. | instruction | 0 | 80,124 | 13 | 160,248 |
Tags: brute force, dfs and similar, graphs, hashing
Correct Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
N, M, K = map(int, input().split())
OUT = [[] for _ in range(N)]
t, m = 12345, (1 << 60) - 1
HASH = []
s = 987654321
H = 0
for _ in range(N):
s = (s * 17 + t) & m
HASH.append(s)
H ^= s
for _ in range(M):
u, v, w = map(int, input().split())
u, v = u-1, v-1
OUT[u].append((w << 18) + v)
X = [[0] * (i+2) for i in range(K)]
m = (1 << 18) - 1
for i in range(N):
c = len(OUT[i])
for j, vw in enumerate(sorted(OUT[i])):
w, v = vw >> 18, vw & m
X[c-1][j] ^= HASH[v]
s = 0
for i in range(K):
s ^= X[i][0]
X[0][0] = 0
ans = 0
A = [0] * K
f = 1
while f:
if s == H:
ans += 1
A[0] += 1
a = 0
while A[a] == a + 1:
s ^= X[a][0]
A[a] = 0
a += 1
if a >= K:
f = 0
break
s ^= X[a][A[a]] ^ X[a][A[a]+1]
A[a] += 1
ans = 0
A = [0] * K
f = 1
while f:
if s == H:
ans += 1
A[0] += 1
a = 0
while A[a] == a + 1:
s ^= X[a][0]
A[a] = 0
a += 1
if a >= K:
f = 0
break
s ^= X[a][A[a]] ^ X[a][A[a]+1]
A[a] += 1
print(ans)
``` | output | 1 | 80,124 | 13 | 160,249 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Boboniu has a directed graph with n vertices and m edges.
The out-degree of each vertex is at most k.
Each edge has an integer weight between 1 and m. No two edges have equal weights.
Boboniu likes to walk on the graph with some specific rules, which is represented by a tuple (c_1,c_2,…,c_k). If he now stands on a vertex u with out-degree i, then he will go to the next vertex by the edge with the c_i-th (1≤ c_i≤ i) smallest weight among all edges outgoing from u.
Now Boboniu asks you to calculate the number of tuples (c_1,c_2,…,c_k) such that
* 1≤ c_i≤ i for all i (1≤ i≤ k).
* Starting from any vertex u, it is possible to go back to u in finite time by walking on the graph under the described rules.
Input
The first line contains three integers n, m and k (2≤ n≤ 2⋅ 10^5, 2≤ m≤ min(2⋅ 10^5,n(n-1) ), 1≤ k≤ 9).
Each of the next m lines contains three integers u, v and w (1≤ u,v≤ n,u≠ v,1≤ w≤ m), denoting an edge from u to v with weight w. It is guaranteed that there are no self-loops or multiple edges and each vertex has at least one edge starting from itself.
It is guaranteed that the out-degree of each vertex is at most k and no two edges have equal weight.
Output
Print one integer: the number of tuples.
Examples
Input
4 6 3
4 2 1
1 2 2
2 4 3
4 1 4
4 3 5
3 1 6
Output
2
Input
5 5 1
1 4 1
5 1 2
2 5 3
4 3 4
3 2 5
Output
1
Input
6 13 4
3 5 1
2 5 2
6 3 3
1 4 4
2 6 5
5 3 6
4 1 7
4 3 8
5 2 9
4 2 10
2 1 11
6 1 12
4 6 13
Output
1
Note
For the first example, there are two tuples: (1,1,3) and (1,2,3). The blue edges in the picture denote the c_i-th smallest edges for each vertex, which Boboniu chooses to go through.
<image>
For the third example, there's only one tuple: (1,2,2,2).
<image>
The out-degree of vertex u means the number of edges outgoing from u. | instruction | 0 | 80,125 | 13 | 160,250 |
Tags: brute force, dfs and similar, graphs, hashing
Correct Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
N, M, K = map(int, input().split())
IN = [[] for _ in range(N)]
OUT = [[] for _ in range(N)]
t, m = 12345, (1 << 60) - 1
HASH = []
s = 987654321
H = 0
for _ in range(N):
s = (s * 17 + t) & m
HASH.append(s)
H ^= s
for _ in range(M):
u, v, w = map(int, input().split())
u, v = u-1, v-1
OUT[u].append((v, w))
X = [[0] * (i+2) for i in range(K+1)]
for i in range(N):
c = len(OUT[i])
for j, (v, w) in enumerate(sorted(OUT[i], key = lambda x: x[1])):
X[c-1][j] ^= HASH[v]
s = 0
for i in range(K):
s ^= X[i][0]
X[0][0] = 0
ans = 0
A = [0] * (K + 1)
f = 1
while f:
if s == H:
ans += 1
s ^= X[1][A[1]] ^ X[1][A[1]+1]
A[1] += 1
a = 1
while A[a] == a + 1:
s ^= X[a][0]
A[a] = 0
a += 1
if a >= K:
f = 0
break
s ^= X[a][A[a]] ^ X[a][A[a]+1]
A[a] += 1
print(ans if K > 1 else min(ans, 1))
``` | output | 1 | 80,125 | 13 | 160,251 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Boboniu has a directed graph with n vertices and m edges.
The out-degree of each vertex is at most k.
Each edge has an integer weight between 1 and m. No two edges have equal weights.
Boboniu likes to walk on the graph with some specific rules, which is represented by a tuple (c_1,c_2,…,c_k). If he now stands on a vertex u with out-degree i, then he will go to the next vertex by the edge with the c_i-th (1≤ c_i≤ i) smallest weight among all edges outgoing from u.
Now Boboniu asks you to calculate the number of tuples (c_1,c_2,…,c_k) such that
* 1≤ c_i≤ i for all i (1≤ i≤ k).
* Starting from any vertex u, it is possible to go back to u in finite time by walking on the graph under the described rules.
Input
The first line contains three integers n, m and k (2≤ n≤ 2⋅ 10^5, 2≤ m≤ min(2⋅ 10^5,n(n-1) ), 1≤ k≤ 9).
Each of the next m lines contains three integers u, v and w (1≤ u,v≤ n,u≠ v,1≤ w≤ m), denoting an edge from u to v with weight w. It is guaranteed that there are no self-loops or multiple edges and each vertex has at least one edge starting from itself.
It is guaranteed that the out-degree of each vertex is at most k and no two edges have equal weight.
Output
Print one integer: the number of tuples.
Examples
Input
4 6 3
4 2 1
1 2 2
2 4 3
4 1 4
4 3 5
3 1 6
Output
2
Input
5 5 1
1 4 1
5 1 2
2 5 3
4 3 4
3 2 5
Output
1
Input
6 13 4
3 5 1
2 5 2
6 3 3
1 4 4
2 6 5
5 3 6
4 1 7
4 3 8
5 2 9
4 2 10
2 1 11
6 1 12
4 6 13
Output
1
Note
For the first example, there are two tuples: (1,1,3) and (1,2,3). The blue edges in the picture denote the c_i-th smallest edges for each vertex, which Boboniu chooses to go through.
<image>
For the third example, there's only one tuple: (1,2,2,2).
<image>
The out-degree of vertex u means the number of edges outgoing from u. | instruction | 0 | 80,126 | 13 | 160,252 |
Tags: brute force, dfs and similar, graphs, hashing
Correct Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
N, M, K = map(int, input().split())
IN = [[] for _ in range(N)]
OUT = [[] for _ in range(N)]
t, m = 12345, (1 << 60) - 1
HASH = []
s = 987654321
H = 0
for _ in range(N):
s = (s * 17 + t) & m
HASH.append(s)
H ^= s
for _ in range(M):
u, v, w = map(int, input().split())
u, v = u-1, v-1
OUT[u].append((v, w))
X = [[0] * (i+2) for i in range(K+1)]
for i in range(N):
c = len(OUT[i])
for j, (v, w) in enumerate(sorted(OUT[i], key = lambda x: x[1])):
X[c-1][j] ^= HASH[v]
Y = [[x[j] ^ x[j+1] for j in range(i+1)] for i, x in enumerate(X)]
s = 0
for i in range(K):
s ^= X[i][0]
X[0][0] = 0
ans = 0
A = [0] * (K + 1)
f = 1
while f:
if s == H:
ans += 1
s ^= Y[1][A[1]]
A[1] += 1
a = 1
while A[a] == a + 1:
s ^= X[a][0]
A[a] = 0
a += 1
if a >= K:
f = 0
break
s ^= Y[a][A[a]]
A[a] += 1
print(ans if K > 1 else min(ans, 1))
``` | output | 1 | 80,126 | 13 | 160,253 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Boboniu has a directed graph with n vertices and m edges.
The out-degree of each vertex is at most k.
Each edge has an integer weight between 1 and m. No two edges have equal weights.
Boboniu likes to walk on the graph with some specific rules, which is represented by a tuple (c_1,c_2,…,c_k). If he now stands on a vertex u with out-degree i, then he will go to the next vertex by the edge with the c_i-th (1≤ c_i≤ i) smallest weight among all edges outgoing from u.
Now Boboniu asks you to calculate the number of tuples (c_1,c_2,…,c_k) such that
* 1≤ c_i≤ i for all i (1≤ i≤ k).
* Starting from any vertex u, it is possible to go back to u in finite time by walking on the graph under the described rules.
Input
The first line contains three integers n, m and k (2≤ n≤ 2⋅ 10^5, 2≤ m≤ min(2⋅ 10^5,n(n-1) ), 1≤ k≤ 9).
Each of the next m lines contains three integers u, v and w (1≤ u,v≤ n,u≠ v,1≤ w≤ m), denoting an edge from u to v with weight w. It is guaranteed that there are no self-loops or multiple edges and each vertex has at least one edge starting from itself.
It is guaranteed that the out-degree of each vertex is at most k and no two edges have equal weight.
Output
Print one integer: the number of tuples.
Examples
Input
4 6 3
4 2 1
1 2 2
2 4 3
4 1 4
4 3 5
3 1 6
Output
2
Input
5 5 1
1 4 1
5 1 2
2 5 3
4 3 4
3 2 5
Output
1
Input
6 13 4
3 5 1
2 5 2
6 3 3
1 4 4
2 6 5
5 3 6
4 1 7
4 3 8
5 2 9
4 2 10
2 1 11
6 1 12
4 6 13
Output
1
Note
For the first example, there are two tuples: (1,1,3) and (1,2,3). The blue edges in the picture denote the c_i-th smallest edges for each vertex, which Boboniu chooses to go through.
<image>
For the third example, there's only one tuple: (1,2,2,2).
<image>
The out-degree of vertex u means the number of edges outgoing from u.
Submitted Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
N, M, K = map(int, input().split())
OUT = [[] for _ in range(N)]
t, m = 12345, (1 << 60) - 1
HASH = []
s = 987654321
H = 0
for _ in range(N):
s = (s * 17 + t) & m
HASH.append(s)
H ^= s
for _ in range(M):
u, v, w = map(int, input().split())
u, v = u-1, v-1
OUT[u].append((w << 18) + v)
X = [[0] * (i+2) for i in range(K)]
m = (1 << 18) - 1
for i in range(N):
c = len(OUT[i])
for j, vw in enumerate(sorted(OUT[i])):
w, v = vw >> 18, vw & m
X[c-1][j] ^= HASH[v]
s = 0
for i in range(K):
s ^= X[i][0]
X[0][0] = 0
ans = 0
A = [0] * K
f = 1
while f:
if s == H:
ans += 1
A[0] += 1
a = 0
while A[a] == a + 1:
s ^= X[a][0]
A[a] = 0
a += 1
if a >= K:
f = 0
break
s ^= X[a][A[a]] ^ X[a][A[a]+1]
A[a] += 1
print(ans)
``` | instruction | 0 | 80,127 | 13 | 160,254 |
Yes | output | 1 | 80,127 | 13 | 160,255 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Boboniu has a directed graph with n vertices and m edges.
The out-degree of each vertex is at most k.
Each edge has an integer weight between 1 and m. No two edges have equal weights.
Boboniu likes to walk on the graph with some specific rules, which is represented by a tuple (c_1,c_2,…,c_k). If he now stands on a vertex u with out-degree i, then he will go to the next vertex by the edge with the c_i-th (1≤ c_i≤ i) smallest weight among all edges outgoing from u.
Now Boboniu asks you to calculate the number of tuples (c_1,c_2,…,c_k) such that
* 1≤ c_i≤ i for all i (1≤ i≤ k).
* Starting from any vertex u, it is possible to go back to u in finite time by walking on the graph under the described rules.
Input
The first line contains three integers n, m and k (2≤ n≤ 2⋅ 10^5, 2≤ m≤ min(2⋅ 10^5,n(n-1) ), 1≤ k≤ 9).
Each of the next m lines contains three integers u, v and w (1≤ u,v≤ n,u≠ v,1≤ w≤ m), denoting an edge from u to v with weight w. It is guaranteed that there are no self-loops or multiple edges and each vertex has at least one edge starting from itself.
It is guaranteed that the out-degree of each vertex is at most k and no two edges have equal weight.
Output
Print one integer: the number of tuples.
Examples
Input
4 6 3
4 2 1
1 2 2
2 4 3
4 1 4
4 3 5
3 1 6
Output
2
Input
5 5 1
1 4 1
5 1 2
2 5 3
4 3 4
3 2 5
Output
1
Input
6 13 4
3 5 1
2 5 2
6 3 3
1 4 4
2 6 5
5 3 6
4 1 7
4 3 8
5 2 9
4 2 10
2 1 11
6 1 12
4 6 13
Output
1
Note
For the first example, there are two tuples: (1,1,3) and (1,2,3). The blue edges in the picture denote the c_i-th smallest edges for each vertex, which Boboniu chooses to go through.
<image>
For the third example, there's only one tuple: (1,2,2,2).
<image>
The out-degree of vertex u means the number of edges outgoing from u.
Submitted Solution:
```
import sys, math
import io, os
data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
#def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write('\n'.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
from decimal import Decimal
from fractions import Fraction
#sys.setrecursionlimit(100000)
INF = float('inf')
mod = int(1e9)+7
def cal(num,l):
if num==k:
S=0
for i in range(k):
S^=val[i][l[i]]
if S==H:
return 1
return 0
else:
ans=0
for i in range(len(l)+1):
ans+=cal(num+1,l+[i])
return ans
n,m,k=mdata()
val=[[0]*k for i in range(k)]
g=[[] for i in range(n)]
for i in range(m):
u,v,w=mdata()
g[u-1].append((w,v-1))
HASH = [4343434343439 + (10 ** 9 + 7) * i for i in range(n + 1)]
H = HASH[0]
for x in HASH:
H ^= x
for i in range(n):
g[i].sort()
for j in range(len(g[i])):
val[len(g[i])-1][j]^=HASH[g[i][j][1]+1]
out(cal(0,[]))
``` | instruction | 0 | 80,128 | 13 | 160,256 |
Yes | output | 1 | 80,128 | 13 | 160,257 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Boboniu has a directed graph with n vertices and m edges.
The out-degree of each vertex is at most k.
Each edge has an integer weight between 1 and m. No two edges have equal weights.
Boboniu likes to walk on the graph with some specific rules, which is represented by a tuple (c_1,c_2,…,c_k). If he now stands on a vertex u with out-degree i, then he will go to the next vertex by the edge with the c_i-th (1≤ c_i≤ i) smallest weight among all edges outgoing from u.
Now Boboniu asks you to calculate the number of tuples (c_1,c_2,…,c_k) such that
* 1≤ c_i≤ i for all i (1≤ i≤ k).
* Starting from any vertex u, it is possible to go back to u in finite time by walking on the graph under the described rules.
Input
The first line contains three integers n, m and k (2≤ n≤ 2⋅ 10^5, 2≤ m≤ min(2⋅ 10^5,n(n-1) ), 1≤ k≤ 9).
Each of the next m lines contains three integers u, v and w (1≤ u,v≤ n,u≠ v,1≤ w≤ m), denoting an edge from u to v with weight w. It is guaranteed that there are no self-loops or multiple edges and each vertex has at least one edge starting from itself.
It is guaranteed that the out-degree of each vertex is at most k and no two edges have equal weight.
Output
Print one integer: the number of tuples.
Examples
Input
4 6 3
4 2 1
1 2 2
2 4 3
4 1 4
4 3 5
3 1 6
Output
2
Input
5 5 1
1 4 1
5 1 2
2 5 3
4 3 4
3 2 5
Output
1
Input
6 13 4
3 5 1
2 5 2
6 3 3
1 4 4
2 6 5
5 3 6
4 1 7
4 3 8
5 2 9
4 2 10
2 1 11
6 1 12
4 6 13
Output
1
Note
For the first example, there are two tuples: (1,1,3) and (1,2,3). The blue edges in the picture denote the c_i-th smallest edges for each vertex, which Boboniu chooses to go through.
<image>
For the third example, there's only one tuple: (1,2,2,2).
<image>
The out-degree of vertex u means the number of edges outgoing from u.
Submitted Solution:
```
from sys import stdin, stdout
import random as r
def dfs(l, v_a, k, wk, rnd):
if l > k:
return 1 if wk == rnd else 0
res = 0
for i in range(1, l+1):
res += dfs(l+1, v_a, k, wk + v_a[l][i], rnd)
return res
def boboniu_walks_on_graph(n, m, k, e_a):
MAX = 2 ** 31 - 1
n_a = [0] * (n + 1)
rnd = 0
v_a = [[0 for _ in range(10)] for _ in range(10)]
for i in range(1, n + 1):
n_a[i] = r.randint(0, MAX)
rnd += n_a[i]
for i in range(1, n + 1):
for j in range(1, len(e_a[i]) + 1):
v_a[len(e_a[i])][j] += n_a[e_a[i][j-1]]
return dfs(1, v_a, k, 0, rnd)
n, m, k = map(int, stdin.readline().split())
e_a = [[] for _ in range(n+1)]
for _ in range(m):
u, v, w = map(int, stdin.readline().split())
e_a[u].append(v)
ans = boboniu_walks_on_graph(n, m, k, e_a)
stdout.write(str(ans) + '\n')
``` | instruction | 0 | 80,129 | 13 | 160,258 |
Yes | output | 1 | 80,129 | 13 | 160,259 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Boboniu has a directed graph with n vertices and m edges.
The out-degree of each vertex is at most k.
Each edge has an integer weight between 1 and m. No two edges have equal weights.
Boboniu likes to walk on the graph with some specific rules, which is represented by a tuple (c_1,c_2,…,c_k). If he now stands on a vertex u with out-degree i, then he will go to the next vertex by the edge with the c_i-th (1≤ c_i≤ i) smallest weight among all edges outgoing from u.
Now Boboniu asks you to calculate the number of tuples (c_1,c_2,…,c_k) such that
* 1≤ c_i≤ i for all i (1≤ i≤ k).
* Starting from any vertex u, it is possible to go back to u in finite time by walking on the graph under the described rules.
Input
The first line contains three integers n, m and k (2≤ n≤ 2⋅ 10^5, 2≤ m≤ min(2⋅ 10^5,n(n-1) ), 1≤ k≤ 9).
Each of the next m lines contains three integers u, v and w (1≤ u,v≤ n,u≠ v,1≤ w≤ m), denoting an edge from u to v with weight w. It is guaranteed that there are no self-loops or multiple edges and each vertex has at least one edge starting from itself.
It is guaranteed that the out-degree of each vertex is at most k and no two edges have equal weight.
Output
Print one integer: the number of tuples.
Examples
Input
4 6 3
4 2 1
1 2 2
2 4 3
4 1 4
4 3 5
3 1 6
Output
2
Input
5 5 1
1 4 1
5 1 2
2 5 3
4 3 4
3 2 5
Output
1
Input
6 13 4
3 5 1
2 5 2
6 3 3
1 4 4
2 6 5
5 3 6
4 1 7
4 3 8
5 2 9
4 2 10
2 1 11
6 1 12
4 6 13
Output
1
Note
For the first example, there are two tuples: (1,1,3) and (1,2,3). The blue edges in the picture denote the c_i-th smallest edges for each vertex, which Boboniu chooses to go through.
<image>
For the third example, there's only one tuple: (1,2,2,2).
<image>
The out-degree of vertex u means the number of edges outgoing from u.
Submitted Solution:
```
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from operator import itemgetter
n,m,k=map(int,input().split()) # 1<=k<=9
E=[[] for i in range(n+1)]
for i in range(m):
u,v,w=map(int,input().split())
E[u].append((w,v))
COME=[[0 for j in range(10)] for i in range(10)]
D=[[0 for j in range(10)] for i in range(10)]
HASH=[4343434343439+(10**9+7)*i for i in range(n+1)]
H=HASH[0]
for x in HASH:
H^=x
for i in range(1,n+1):
E[i].sort(key=itemgetter(0))
L=len(E[i])
for j in range(L):
COME[L][j]^=HASH[E[i][j][1]]
D[L][j]+=1
ANS=[0]
def dfs(number,l):
if number==k+1:
#print(l)
C=0
DX=0
for i in range(k):
C^=COME[i+1][l[i]]
DX+=D[i+1][l[i]]
if C==H and DX==n:
#print(l)
ANS[0]+=1
return
for i in range(number):
dfs(number+1,l+[i])
dfs(1,[])
print(ANS[0])
``` | instruction | 0 | 80,130 | 13 | 160,260 |
Yes | output | 1 | 80,130 | 13 | 160,261 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Boboniu has a directed graph with n vertices and m edges.
The out-degree of each vertex is at most k.
Each edge has an integer weight between 1 and m. No two edges have equal weights.
Boboniu likes to walk on the graph with some specific rules, which is represented by a tuple (c_1,c_2,…,c_k). If he now stands on a vertex u with out-degree i, then he will go to the next vertex by the edge with the c_i-th (1≤ c_i≤ i) smallest weight among all edges outgoing from u.
Now Boboniu asks you to calculate the number of tuples (c_1,c_2,…,c_k) such that
* 1≤ c_i≤ i for all i (1≤ i≤ k).
* Starting from any vertex u, it is possible to go back to u in finite time by walking on the graph under the described rules.
Input
The first line contains three integers n, m and k (2≤ n≤ 2⋅ 10^5, 2≤ m≤ min(2⋅ 10^5,n(n-1) ), 1≤ k≤ 9).
Each of the next m lines contains three integers u, v and w (1≤ u,v≤ n,u≠ v,1≤ w≤ m), denoting an edge from u to v with weight w. It is guaranteed that there are no self-loops or multiple edges and each vertex has at least one edge starting from itself.
It is guaranteed that the out-degree of each vertex is at most k and no two edges have equal weight.
Output
Print one integer: the number of tuples.
Examples
Input
4 6 3
4 2 1
1 2 2
2 4 3
4 1 4
4 3 5
3 1 6
Output
2
Input
5 5 1
1 4 1
5 1 2
2 5 3
4 3 4
3 2 5
Output
1
Input
6 13 4
3 5 1
2 5 2
6 3 3
1 4 4
2 6 5
5 3 6
4 1 7
4 3 8
5 2 9
4 2 10
2 1 11
6 1 12
4 6 13
Output
1
Note
For the first example, there are two tuples: (1,1,3) and (1,2,3). The blue edges in the picture denote the c_i-th smallest edges for each vertex, which Boboniu chooses to go through.
<image>
For the third example, there's only one tuple: (1,2,2,2).
<image>
The out-degree of vertex u means the number of edges outgoing from u.
Submitted Solution:
```
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write('\n'.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
from decimal import Decimal
from fractions import Fraction
#sys.setrecursionlimit(100000)
INF = float('inf')
mod = int(1e9)+7
def cal(num,l):
if num==k:
S=0
for i in range(k):
S+=val[i][l[i]]
if S==H:
return 1
return 0
else:
ans=0
for i in range(len(l)+1):
ans+=cal(num+1,l+[i])
return ans
n,m,k=mdata()
val=[[0]*k for i in range(k)]
g=[[] for i in range(n)]
for i in range(m):
u,v,w=mdata()
g[u-1].append((w,v-1))
HASH = [4343434343439 + (10 ** 9 + 7) * i for i in range(n + 1)]
H = 0
for x in HASH[1:]:
H += x
for i in range(n):
g[i].sort()
for j in range(len(g[i])):
val[len(g[i])-1][j]+=HASH[g[i][j][1]+1]
out(cal(0,[]))
``` | instruction | 0 | 80,131 | 13 | 160,262 |
No | output | 1 | 80,131 | 13 | 160,263 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Boboniu has a directed graph with n vertices and m edges.
The out-degree of each vertex is at most k.
Each edge has an integer weight between 1 and m. No two edges have equal weights.
Boboniu likes to walk on the graph with some specific rules, which is represented by a tuple (c_1,c_2,…,c_k). If he now stands on a vertex u with out-degree i, then he will go to the next vertex by the edge with the c_i-th (1≤ c_i≤ i) smallest weight among all edges outgoing from u.
Now Boboniu asks you to calculate the number of tuples (c_1,c_2,…,c_k) such that
* 1≤ c_i≤ i for all i (1≤ i≤ k).
* Starting from any vertex u, it is possible to go back to u in finite time by walking on the graph under the described rules.
Input
The first line contains three integers n, m and k (2≤ n≤ 2⋅ 10^5, 2≤ m≤ min(2⋅ 10^5,n(n-1) ), 1≤ k≤ 9).
Each of the next m lines contains three integers u, v and w (1≤ u,v≤ n,u≠ v,1≤ w≤ m), denoting an edge from u to v with weight w. It is guaranteed that there are no self-loops or multiple edges and each vertex has at least one edge starting from itself.
It is guaranteed that the out-degree of each vertex is at most k and no two edges have equal weight.
Output
Print one integer: the number of tuples.
Examples
Input
4 6 3
4 2 1
1 2 2
2 4 3
4 1 4
4 3 5
3 1 6
Output
2
Input
5 5 1
1 4 1
5 1 2
2 5 3
4 3 4
3 2 5
Output
1
Input
6 13 4
3 5 1
2 5 2
6 3 3
1 4 4
2 6 5
5 3 6
4 1 7
4 3 8
5 2 9
4 2 10
2 1 11
6 1 12
4 6 13
Output
1
Note
For the first example, there are two tuples: (1,1,3) and (1,2,3). The blue edges in the picture denote the c_i-th smallest edges for each vertex, which Boboniu chooses to go through.
<image>
For the third example, there's only one tuple: (1,2,2,2).
<image>
The out-degree of vertex u means the number of edges outgoing from u.
Submitted Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
N, M, K = map(int, input().split())
IN = [[] for _ in range(N)]
OUT = [[] for _ in range(N)]
t, m = 12345, (1 << 60) - 1
HASH = []
s = 987654321
H = 0
for _ in range(N):
s = (s * 17 + t) & m
HASH.append(s)
H ^= s
for _ in range(M):
u, v, w = map(int, input().split())
u, v = u-1, v-1
OUT[u].append((v, w))
X = [[0] * (i+2) for i in range(K+1)]
for i in range(N):
c = len(OUT[i])
for j, (v, w) in enumerate(sorted(OUT[i], key = lambda x: x[1])):
X[c-1][j] ^= HASH[v]
s = 0
for i in range(K):
s ^= X[i][0]
X[0][0] = 0
ans = 0
A = [0] * (K + 1)
f = 1
while f:
if s == H:
ans += 1
s ^= X[1][A[1]] ^ X[1][A[1]+1]
A[1] += 1
a = 1
while A[a] == a + 1:
s ^= X[a][0]
A[a] = 0
a += 1
if a >= K:
f = 0
break
s ^= X[a][A[a]] ^ X[a][A[a]+1]
A[a] += 1
print(ans)
``` | instruction | 0 | 80,132 | 13 | 160,264 |
No | output | 1 | 80,132 | 13 | 160,265 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Boboniu has a directed graph with n vertices and m edges.
The out-degree of each vertex is at most k.
Each edge has an integer weight between 1 and m. No two edges have equal weights.
Boboniu likes to walk on the graph with some specific rules, which is represented by a tuple (c_1,c_2,…,c_k). If he now stands on a vertex u with out-degree i, then he will go to the next vertex by the edge with the c_i-th (1≤ c_i≤ i) smallest weight among all edges outgoing from u.
Now Boboniu asks you to calculate the number of tuples (c_1,c_2,…,c_k) such that
* 1≤ c_i≤ i for all i (1≤ i≤ k).
* Starting from any vertex u, it is possible to go back to u in finite time by walking on the graph under the described rules.
Input
The first line contains three integers n, m and k (2≤ n≤ 2⋅ 10^5, 2≤ m≤ min(2⋅ 10^5,n(n-1) ), 1≤ k≤ 9).
Each of the next m lines contains three integers u, v and w (1≤ u,v≤ n,u≠ v,1≤ w≤ m), denoting an edge from u to v with weight w. It is guaranteed that there are no self-loops or multiple edges and each vertex has at least one edge starting from itself.
It is guaranteed that the out-degree of each vertex is at most k and no two edges have equal weight.
Output
Print one integer: the number of tuples.
Examples
Input
4 6 3
4 2 1
1 2 2
2 4 3
4 1 4
4 3 5
3 1 6
Output
2
Input
5 5 1
1 4 1
5 1 2
2 5 3
4 3 4
3 2 5
Output
1
Input
6 13 4
3 5 1
2 5 2
6 3 3
1 4 4
2 6 5
5 3 6
4 1 7
4 3 8
5 2 9
4 2 10
2 1 11
6 1 12
4 6 13
Output
1
Note
For the first example, there are two tuples: (1,1,3) and (1,2,3). The blue edges in the picture denote the c_i-th smallest edges for each vertex, which Boboniu chooses to go through.
<image>
For the third example, there's only one tuple: (1,2,2,2).
<image>
The out-degree of vertex u means the number of edges outgoing from u.
Submitted Solution:
```
import sys
input = sys.stdin.buffer.readline
n,m,k = map(int,input().split())
edge = [[] for _ in range(n)]
dg = 10**6
MOD = 10**9+7
for _ in range(m):
u,v,w = map(int,input().split())
edge[u-1].append(w*dg + v-1)
num = [[] for i in range(k+1)]
one = set()
for i in range(n):
num[len(edge[i])].append(i)
edge[i].sort()
q = [[0]*(k+1) for i in range(k+1)]
for i in range(1,k+1):
for j in range(i):
for e in num[i]:
go = edge[e][j]%dg
q[i][j] = (q[i][j] + (go*go+12231312)*1213 + 12316)%MOD
cor = 0
for i in range(n):
cor = (cor + (i*i+12231312)*1213 + 12316)%MOD
print(cor)
fac = 1
for i in range(2,k+1):
fac *= i
res = 0
for w in range(1,fac+1):
tmp = w
nxt = 0
tank = []
for r in range(k,0,-1):
tmp,c = divmod(tmp,r)
tank.append(c)
nxt = (nxt + q[r][c])%MOD
if nxt == cor:
res += 1
print(res)
``` | instruction | 0 | 80,133 | 13 | 160,266 |
No | output | 1 | 80,133 | 13 | 160,267 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Boboniu has a directed graph with n vertices and m edges.
The out-degree of each vertex is at most k.
Each edge has an integer weight between 1 and m. No two edges have equal weights.
Boboniu likes to walk on the graph with some specific rules, which is represented by a tuple (c_1,c_2,…,c_k). If he now stands on a vertex u with out-degree i, then he will go to the next vertex by the edge with the c_i-th (1≤ c_i≤ i) smallest weight among all edges outgoing from u.
Now Boboniu asks you to calculate the number of tuples (c_1,c_2,…,c_k) such that
* 1≤ c_i≤ i for all i (1≤ i≤ k).
* Starting from any vertex u, it is possible to go back to u in finite time by walking on the graph under the described rules.
Input
The first line contains three integers n, m and k (2≤ n≤ 2⋅ 10^5, 2≤ m≤ min(2⋅ 10^5,n(n-1) ), 1≤ k≤ 9).
Each of the next m lines contains three integers u, v and w (1≤ u,v≤ n,u≠ v,1≤ w≤ m), denoting an edge from u to v with weight w. It is guaranteed that there are no self-loops or multiple edges and each vertex has at least one edge starting from itself.
It is guaranteed that the out-degree of each vertex is at most k and no two edges have equal weight.
Output
Print one integer: the number of tuples.
Examples
Input
4 6 3
4 2 1
1 2 2
2 4 3
4 1 4
4 3 5
3 1 6
Output
2
Input
5 5 1
1 4 1
5 1 2
2 5 3
4 3 4
3 2 5
Output
1
Input
6 13 4
3 5 1
2 5 2
6 3 3
1 4 4
2 6 5
5 3 6
4 1 7
4 3 8
5 2 9
4 2 10
2 1 11
6 1 12
4 6 13
Output
1
Note
For the first example, there are two tuples: (1,1,3) and (1,2,3). The blue edges in the picture denote the c_i-th smallest edges for each vertex, which Boboniu chooses to go through.
<image>
For the third example, there's only one tuple: (1,2,2,2).
<image>
The out-degree of vertex u means the number of edges outgoing from u.
Submitted Solution:
```
import sys
input = sys.stdin.buffer.readline
n,m,k = map(int,input().split())
edge = [[] for _ in range(n)]
dg = 10**6
MOD = 10**9+7
for _ in range(m):
u,v,w = map(int,input().split())
edge[u-1].append(w*dg + v-1)
num = [[] for i in range(k+1)]
one = set()
for i in range(n):
num[len(edge[i])].append(i)
edge[i].sort()
q = [[0]*(k+1) for i in range(k+1)]
for i in range(1,k+1):
for j in range(i):
for e in num[i]:
go = edge[e][j]%dg
q[i][j] = (q[i][j] + (go+122)*13 + 16)%MOD
cor = 0
for i in range(n):
cor = (cor + (i+122)*13 + 16)%MOD
fac = 1
for i in range(2,k+1):
fac *= i
res = 0
for w in range(1,fac+1):
tmp = w
nxt = 0
for r in range(k,0,-1):
tmp,c = divmod(tmp,r)
nxt = (nxt + q[r][c])%MOD
if nxt == cor:
res += 1
print(res)
``` | instruction | 0 | 80,134 | 13 | 160,268 |
No | output | 1 | 80,134 | 13 | 160,269 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera conducts experiments with algorithms that search for shortest paths. He has recently studied the Floyd's algorithm, so it's time to work with it.
Valera's already written the code that counts the shortest distance between any pair of vertexes in a non-directed connected graph from n vertexes and m edges, containing no loops and multiple edges. Besides, Valera's decided to mark part of the vertexes. He's marked exactly k vertexes a1, a2, ..., ak.
Valera's code is given below.
ans[i][j] // the shortest distance for a pair of vertexes i, j
a[i] // vertexes, marked by Valera
for(i = 1; i <= n; i++) {
for(j = 1; j <= n; j++) {
if (i == j)
ans[i][j] = 0;
else
ans[i][j] = INF; //INF is a very large number
}
}
for(i = 1; i <= m; i++) {
read a pair of vertexes u, v that have a non-directed edge between them;
ans[u][v] = 1;
ans[v][u] = 1;
}
for (i = 1; i <= k; i++) {
v = a[i];
for(j = 1; j <= n; j++)
for(r = 1; r <= n; r++)
ans[j][r] = min(ans[j][r], ans[j][v] + ans[v][r]);
}
Valera has seen that his code is wrong. Help the boy. Given the set of marked vertexes a1, a2, ..., ak, find such non-directed connected graph, consisting of n vertexes and m edges, for which Valera's code counts the wrong shortest distance for at least one pair of vertexes (i, j). Valera is really keen to get a graph without any loops and multiple edges. If no such graph exists, print -1.
Input
The first line of the input contains three integers n, m, k (3 ≤ n ≤ 300, 2 ≤ k ≤ n , <image>) — the number of vertexes, the number of edges and the number of marked vertexes.
The second line of the input contains k space-separated integers a1, a2, ... ak (1 ≤ ai ≤ n) — the numbers of the marked vertexes. It is guaranteed that all numbers ai are distinct.
Output
If the graph doesn't exist, print -1 on a single line. Otherwise, print m lines, each containing two integers u, v — the description of the edges of the graph Valera's been looking for.
Examples
Input
3 2 2
1 2
Output
1 3
2 3
Input
3 3 2
1 2
Output
-1 | instruction | 0 | 80,297 | 13 | 160,594 |
Tags: brute force, constructive algorithms, dfs and similar, graphs
Correct Solution:
```
# written with help of editorial
n, m, k = map(int, input().split())
ban = list(map(int, input().split()))
if k == n or m > n * (n - 1) // 2 - k + 1:
print('-1')
else:
edges = [(i, j) for i in range(1, n + 1) for j in range(i + 1, n + 1)]
for i in range(1, k):
a = min(ban[i], ban[0])
b = max(ban[i], ban[0])
edges.remove((a, b))
special = None
for i in range(n):
if i + 1 not in ban:
special = i
break
for i in range(n):
if special == i:
continue
a = min(special, i) + 1
b = max(special, i) + 1
print(a, b)
m -= 1
edges.remove((a, b))
for x in edges[:m]:
print(x[0], x[1])
``` | output | 1 | 80,297 | 13 | 160,595 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera conducts experiments with algorithms that search for shortest paths. He has recently studied the Floyd's algorithm, so it's time to work with it.
Valera's already written the code that counts the shortest distance between any pair of vertexes in a non-directed connected graph from n vertexes and m edges, containing no loops and multiple edges. Besides, Valera's decided to mark part of the vertexes. He's marked exactly k vertexes a1, a2, ..., ak.
Valera's code is given below.
ans[i][j] // the shortest distance for a pair of vertexes i, j
a[i] // vertexes, marked by Valera
for(i = 1; i <= n; i++) {
for(j = 1; j <= n; j++) {
if (i == j)
ans[i][j] = 0;
else
ans[i][j] = INF; //INF is a very large number
}
}
for(i = 1; i <= m; i++) {
read a pair of vertexes u, v that have a non-directed edge between them;
ans[u][v] = 1;
ans[v][u] = 1;
}
for (i = 1; i <= k; i++) {
v = a[i];
for(j = 1; j <= n; j++)
for(r = 1; r <= n; r++)
ans[j][r] = min(ans[j][r], ans[j][v] + ans[v][r]);
}
Valera has seen that his code is wrong. Help the boy. Given the set of marked vertexes a1, a2, ..., ak, find such non-directed connected graph, consisting of n vertexes and m edges, for which Valera's code counts the wrong shortest distance for at least one pair of vertexes (i, j). Valera is really keen to get a graph without any loops and multiple edges. If no such graph exists, print -1.
Input
The first line of the input contains three integers n, m, k (3 ≤ n ≤ 300, 2 ≤ k ≤ n , <image>) — the number of vertexes, the number of edges and the number of marked vertexes.
The second line of the input contains k space-separated integers a1, a2, ... ak (1 ≤ ai ≤ n) — the numbers of the marked vertexes. It is guaranteed that all numbers ai are distinct.
Output
If the graph doesn't exist, print -1 on a single line. Otherwise, print m lines, each containing two integers u, v — the description of the edges of the graph Valera's been looking for.
Examples
Input
3 2 2
1 2
Output
1 3
2 3
Input
3 3 2
1 2
Output
-1 | instruction | 0 | 80,298 | 13 | 160,596 |
Tags: brute force, constructive algorithms, dfs and similar, graphs
Correct Solution:
```
import sys
n, m, k = list(map(int, input().split()))
if (m > n*(n-1)//2 - k + 1 or k == n):
print(-1)
sys.exit()
kek = set()
def add_edge(i, j):
global m
global kek
if (m <= 0): return
if ((i, j) in kek): return
print(i, j)
kek.add((i, j))
kek.add((j, i))
m-=1
mark = list(map(int, input().split()))
notmark = []
for i in range(1, n+1):
if i in mark: continue
notmark.append(i)
add_edge(mark[0], notmark[0])
for i in range(len(notmark) - 1):
add_edge(notmark[i], notmark[i+1])
add_edge(notmark[-1], mark[1])
for i in range(1, len(mark) - 1):
add_edge(mark[i], mark[i+1])
for i in notmark:
for j in mark: add_edge(i, j)
for i in range(1, len(mark)):
for j in range(i+1, len(mark)):
add_edge(mark[i], mark[j])
for i in range(len(notmark)):
for j in range(i+1, len(notmark)):
add_edge(notmark[i], notmark[j])
# Thu Jul 30 2020 03:06:13 GMT+0300 (Москва, стандартное время)
``` | output | 1 | 80,298 | 13 | 160,597 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera conducts experiments with algorithms that search for shortest paths. He has recently studied the Floyd's algorithm, so it's time to work with it.
Valera's already written the code that counts the shortest distance between any pair of vertexes in a non-directed connected graph from n vertexes and m edges, containing no loops and multiple edges. Besides, Valera's decided to mark part of the vertexes. He's marked exactly k vertexes a1, a2, ..., ak.
Valera's code is given below.
ans[i][j] // the shortest distance for a pair of vertexes i, j
a[i] // vertexes, marked by Valera
for(i = 1; i <= n; i++) {
for(j = 1; j <= n; j++) {
if (i == j)
ans[i][j] = 0;
else
ans[i][j] = INF; //INF is a very large number
}
}
for(i = 1; i <= m; i++) {
read a pair of vertexes u, v that have a non-directed edge between them;
ans[u][v] = 1;
ans[v][u] = 1;
}
for (i = 1; i <= k; i++) {
v = a[i];
for(j = 1; j <= n; j++)
for(r = 1; r <= n; r++)
ans[j][r] = min(ans[j][r], ans[j][v] + ans[v][r]);
}
Valera has seen that his code is wrong. Help the boy. Given the set of marked vertexes a1, a2, ..., ak, find such non-directed connected graph, consisting of n vertexes and m edges, for which Valera's code counts the wrong shortest distance for at least one pair of vertexes (i, j). Valera is really keen to get a graph without any loops and multiple edges. If no such graph exists, print -1.
Input
The first line of the input contains three integers n, m, k (3 ≤ n ≤ 300, 2 ≤ k ≤ n , <image>) — the number of vertexes, the number of edges and the number of marked vertexes.
The second line of the input contains k space-separated integers a1, a2, ... ak (1 ≤ ai ≤ n) — the numbers of the marked vertexes. It is guaranteed that all numbers ai are distinct.
Output
If the graph doesn't exist, print -1 on a single line. Otherwise, print m lines, each containing two integers u, v — the description of the edges of the graph Valera's been looking for.
Examples
Input
3 2 2
1 2
Output
1 3
2 3
Input
3 3 2
1 2
Output
-1 | instruction | 0 | 80,299 | 13 | 160,598 |
Tags: brute force, constructive algorithms, dfs and similar, graphs
Correct Solution:
```
#!/usr/bin/python3
def readln(): return tuple(map(int, input().split()))
n, m, k = readln()
a = sorted(readln())
if k == n:
print(-1)
else:
b = []
for _ in range(1, n + 1):
if _ not in a:
b.append(_)
uses = [[0]*(n + 1) for _ in range(n + 1)]
if b[0] == 1:
uses[a[0]][a[1]] = uses[a[1]][a[0]] = 1
for _ in a:
uses[_][a[0]] = uses[a[0]][_] = 1
ans = []
for i in range(1, n + 1):
uses[i][i] = 1
if not uses[b[0]][i]:
ans.append((b[0], i))
uses[b[0]][i] = uses[i][b[0]] = 1
for i in range(1, n + 1):
for j in range(i + 1, n + 1):
if not uses[i][j]:
ans.append((i, j))
uses[i][j] = uses[j][i] = 1
if len(ans) >= m:
for e in ans[:m]:
print(*e)
else:
print(-1)
``` | output | 1 | 80,299 | 13 | 160,599 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera conducts experiments with algorithms that search for shortest paths. He has recently studied the Floyd's algorithm, so it's time to work with it.
Valera's already written the code that counts the shortest distance between any pair of vertexes in a non-directed connected graph from n vertexes and m edges, containing no loops and multiple edges. Besides, Valera's decided to mark part of the vertexes. He's marked exactly k vertexes a1, a2, ..., ak.
Valera's code is given below.
ans[i][j] // the shortest distance for a pair of vertexes i, j
a[i] // vertexes, marked by Valera
for(i = 1; i <= n; i++) {
for(j = 1; j <= n; j++) {
if (i == j)
ans[i][j] = 0;
else
ans[i][j] = INF; //INF is a very large number
}
}
for(i = 1; i <= m; i++) {
read a pair of vertexes u, v that have a non-directed edge between them;
ans[u][v] = 1;
ans[v][u] = 1;
}
for (i = 1; i <= k; i++) {
v = a[i];
for(j = 1; j <= n; j++)
for(r = 1; r <= n; r++)
ans[j][r] = min(ans[j][r], ans[j][v] + ans[v][r]);
}
Valera has seen that his code is wrong. Help the boy. Given the set of marked vertexes a1, a2, ..., ak, find such non-directed connected graph, consisting of n vertexes and m edges, for which Valera's code counts the wrong shortest distance for at least one pair of vertexes (i, j). Valera is really keen to get a graph without any loops and multiple edges. If no such graph exists, print -1.
Input
The first line of the input contains three integers n, m, k (3 ≤ n ≤ 300, 2 ≤ k ≤ n , <image>) — the number of vertexes, the number of edges and the number of marked vertexes.
The second line of the input contains k space-separated integers a1, a2, ... ak (1 ≤ ai ≤ n) — the numbers of the marked vertexes. It is guaranteed that all numbers ai are distinct.
Output
If the graph doesn't exist, print -1 on a single line. Otherwise, print m lines, each containing two integers u, v — the description of the edges of the graph Valera's been looking for.
Examples
Input
3 2 2
1 2
Output
1 3
2 3
Input
3 3 2
1 2
Output
-1
Submitted Solution:
```
#!/usr/bin/python3
def readln(): return tuple(map(int, input().split()))
n, m, k = readln()
a = sorted(readln())
if k == n:
print(-1)
else:
b = []
for _ in range(1, n + 1):
if _ not in a:
b.append(_)
uses = [[0]*(n + 1) for _ in range(n + 1)]
if b[0] == 1:
uses[a[0]][a[1]] = uses[a[1]][a[0]] = 1
for _ in a:
uses[_][a[0]] = uses[a[0]][_] = 1
uses[_][a[1]] = uses[a[1]][_] = 1
ans = []
for i in range(1, n + 1):
uses[i][i] = 1
if not uses[b[0]][i]:
ans.append((b[0], i))
uses[b[0]][i] = uses[i][b[0]] = 1
for i in range(1, n + 1):
for j in range(i + 1, n + 1):
if not uses[i][j]:
ans.append((i, j))
uses[i][j] = uses[j][i] = 1
if len(ans) >= m:
for e in ans[:m]:
print(*e)
else:
print(-1)
``` | instruction | 0 | 80,300 | 13 | 160,600 |
No | output | 1 | 80,300 | 13 | 160,601 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera conducts experiments with algorithms that search for shortest paths. He has recently studied the Floyd's algorithm, so it's time to work with it.
Valera's already written the code that counts the shortest distance between any pair of vertexes in a non-directed connected graph from n vertexes and m edges, containing no loops and multiple edges. Besides, Valera's decided to mark part of the vertexes. He's marked exactly k vertexes a1, a2, ..., ak.
Valera's code is given below.
ans[i][j] // the shortest distance for a pair of vertexes i, j
a[i] // vertexes, marked by Valera
for(i = 1; i <= n; i++) {
for(j = 1; j <= n; j++) {
if (i == j)
ans[i][j] = 0;
else
ans[i][j] = INF; //INF is a very large number
}
}
for(i = 1; i <= m; i++) {
read a pair of vertexes u, v that have a non-directed edge between them;
ans[u][v] = 1;
ans[v][u] = 1;
}
for (i = 1; i <= k; i++) {
v = a[i];
for(j = 1; j <= n; j++)
for(r = 1; r <= n; r++)
ans[j][r] = min(ans[j][r], ans[j][v] + ans[v][r]);
}
Valera has seen that his code is wrong. Help the boy. Given the set of marked vertexes a1, a2, ..., ak, find such non-directed connected graph, consisting of n vertexes and m edges, for which Valera's code counts the wrong shortest distance for at least one pair of vertexes (i, j). Valera is really keen to get a graph without any loops and multiple edges. If no such graph exists, print -1.
Input
The first line of the input contains three integers n, m, k (3 ≤ n ≤ 300, 2 ≤ k ≤ n , <image>) — the number of vertexes, the number of edges and the number of marked vertexes.
The second line of the input contains k space-separated integers a1, a2, ... ak (1 ≤ ai ≤ n) — the numbers of the marked vertexes. It is guaranteed that all numbers ai are distinct.
Output
If the graph doesn't exist, print -1 on a single line. Otherwise, print m lines, each containing two integers u, v — the description of the edges of the graph Valera's been looking for.
Examples
Input
3 2 2
1 2
Output
1 3
2 3
Input
3 3 2
1 2
Output
-1
Submitted Solution:
```
import sys
n, m, k = list(map(int, input().split()))
if (m > n*(n-1)//2 - k + 1 or k == n):
print(-1)
sys.exit()
def add_edge(i, j):
global m
if (m <= 0): return
print(i, j)
m-=1
mark = list(map(int, input().split()))
notmark = []
for i in range(1, n+1):
if i in mark: continue
notmark.append(i)
add_edge(mark[0], notmark[0])
for i in range(len(notmark) - 1):
add_edge(notmark[i], notmark[i+1])
add_edge(notmark[-1], mark[1])
for i in range(1, len(mark) - 1):
add_edge(mark[i], mark[i+1])
for i in notmark:
for j in mark: add_edge(i, j)
for i in range(1, len(mark)):
for j in range(i+1, len(mark)):
add_edge(mark[i], mark[j])
for i in range(len(notmark)):
for j in range(i+1, len(notmark)):
add_edge(notmark[i], notmark[j])
# Thu Jul 30 2020 03:00:29 GMT+0300 (Москва, стандартное время)
``` | instruction | 0 | 80,301 | 13 | 160,602 |
No | output | 1 | 80,301 | 13 | 160,603 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera conducts experiments with algorithms that search for shortest paths. He has recently studied the Floyd's algorithm, so it's time to work with it.
Valera's already written the code that counts the shortest distance between any pair of vertexes in a non-directed connected graph from n vertexes and m edges, containing no loops and multiple edges. Besides, Valera's decided to mark part of the vertexes. He's marked exactly k vertexes a1, a2, ..., ak.
Valera's code is given below.
ans[i][j] // the shortest distance for a pair of vertexes i, j
a[i] // vertexes, marked by Valera
for(i = 1; i <= n; i++) {
for(j = 1; j <= n; j++) {
if (i == j)
ans[i][j] = 0;
else
ans[i][j] = INF; //INF is a very large number
}
}
for(i = 1; i <= m; i++) {
read a pair of vertexes u, v that have a non-directed edge between them;
ans[u][v] = 1;
ans[v][u] = 1;
}
for (i = 1; i <= k; i++) {
v = a[i];
for(j = 1; j <= n; j++)
for(r = 1; r <= n; r++)
ans[j][r] = min(ans[j][r], ans[j][v] + ans[v][r]);
}
Valera has seen that his code is wrong. Help the boy. Given the set of marked vertexes a1, a2, ..., ak, find such non-directed connected graph, consisting of n vertexes and m edges, for which Valera's code counts the wrong shortest distance for at least one pair of vertexes (i, j). Valera is really keen to get a graph without any loops and multiple edges. If no such graph exists, print -1.
Input
The first line of the input contains three integers n, m, k (3 ≤ n ≤ 300, 2 ≤ k ≤ n , <image>) — the number of vertexes, the number of edges and the number of marked vertexes.
The second line of the input contains k space-separated integers a1, a2, ... ak (1 ≤ ai ≤ n) — the numbers of the marked vertexes. It is guaranteed that all numbers ai are distinct.
Output
If the graph doesn't exist, print -1 on a single line. Otherwise, print m lines, each containing two integers u, v — the description of the edges of the graph Valera's been looking for.
Examples
Input
3 2 2
1 2
Output
1 3
2 3
Input
3 3 2
1 2
Output
-1
Submitted Solution:
```
n, m, k = map(int, input().split())
if k == n or m > n * (n - 1) // 2 - k + 1:
print('-1')
else:
ban = list(map(int, input().split()))
edges = [(i, j) for i in range(1, n + 1) for j in range(i + 1, n + 1)]
if n <= 3:
for i in range(k - 1):
a = min(ban[i + 1], ban[i])
b = max(ban[i + 1], ban[i])
edges.remove((a, b))
else:
special = None
for i in range(1, n + 1):
if i not in ban:
special = i
break
for i in range(k):
a = min(special, ban[i])
b = max(special, ban[i])
edges.remove((a, b))
if n > 3 and m > n * (n - 1) // 2 - k:
print('-1')
else:
for x in edges:
print(x[0], x[1])
``` | instruction | 0 | 80,302 | 13 | 160,604 |
No | output | 1 | 80,302 | 13 | 160,605 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera conducts experiments with algorithms that search for shortest paths. He has recently studied the Floyd's algorithm, so it's time to work with it.
Valera's already written the code that counts the shortest distance between any pair of vertexes in a non-directed connected graph from n vertexes and m edges, containing no loops and multiple edges. Besides, Valera's decided to mark part of the vertexes. He's marked exactly k vertexes a1, a2, ..., ak.
Valera's code is given below.
ans[i][j] // the shortest distance for a pair of vertexes i, j
a[i] // vertexes, marked by Valera
for(i = 1; i <= n; i++) {
for(j = 1; j <= n; j++) {
if (i == j)
ans[i][j] = 0;
else
ans[i][j] = INF; //INF is a very large number
}
}
for(i = 1; i <= m; i++) {
read a pair of vertexes u, v that have a non-directed edge between them;
ans[u][v] = 1;
ans[v][u] = 1;
}
for (i = 1; i <= k; i++) {
v = a[i];
for(j = 1; j <= n; j++)
for(r = 1; r <= n; r++)
ans[j][r] = min(ans[j][r], ans[j][v] + ans[v][r]);
}
Valera has seen that his code is wrong. Help the boy. Given the set of marked vertexes a1, a2, ..., ak, find such non-directed connected graph, consisting of n vertexes and m edges, for which Valera's code counts the wrong shortest distance for at least one pair of vertexes (i, j). Valera is really keen to get a graph without any loops and multiple edges. If no such graph exists, print -1.
Input
The first line of the input contains three integers n, m, k (3 ≤ n ≤ 300, 2 ≤ k ≤ n , <image>) — the number of vertexes, the number of edges and the number of marked vertexes.
The second line of the input contains k space-separated integers a1, a2, ... ak (1 ≤ ai ≤ n) — the numbers of the marked vertexes. It is guaranteed that all numbers ai are distinct.
Output
If the graph doesn't exist, print -1 on a single line. Otherwise, print m lines, each containing two integers u, v — the description of the edges of the graph Valera's been looking for.
Examples
Input
3 2 2
1 2
Output
1 3
2 3
Input
3 3 2
1 2
Output
-1
Submitted Solution:
```
import sys
n, m, k = list(map(int, input().split()))
if (m > n*(n-1)//2 - k + 1 or k == n):
print(-1)
sys.exit()
def add_edge(i, j):
if (m <= 0): return
print(i, j)
mark = list(map(int, input().split()))
notmark = []
for i in range(1, n+1):
if i in mark: continue
notmark.append(i)
for i in notmark:
for j in mark: add_edge(i, j)
for i in range(1, len(mark)):
for j in range(i+1, len(mark)):
add_edge(mark[i], mark[j])
for i in range(len(notmark)):
for j in range(i+1, len(notmark)):
add_edge(notmark[i], notmark[j])
# Thu Jul 30 2020 02:52:40 GMT+0300 (Москва, стандартное время)
``` | instruction | 0 | 80,303 | 13 | 160,606 |
No | output | 1 | 80,303 | 13 | 160,607 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
The judge has a hidden rooted full binary tree with n leaves. A full binary tree is one where every node has either 0 or 2 children. The nodes with 0 children are called the leaves of the tree. Since this is a full binary tree, there are exactly 2n - 1 nodes in the tree. The leaves of the judge's tree has labels from 1 to n. You would like to reconstruct a tree that is isomorphic to the judge's tree. To do this, you can ask some questions.
A question consists of printing the label of three distinct leaves a1, a2, a3. Let the depth of a node be the shortest distance from the node to the root of the tree. Let LCA(a, b) denote the node with maximum depth that is a common ancestor of the nodes a and b.
Consider X = LCA(a1, a2), Y = LCA(a2, a3), Z = LCA(a3, a1). The judge will tell you which one of X, Y, Z has the maximum depth. Note, this pair is uniquely determined since the tree is a binary tree; there can't be any ties.
More specifically, if X (or Y, Z respectively) maximizes the depth, the judge will respond with the string "X" (or "Y", "Z" respectively).
You may only ask at most 10·n questions.
Input
The first line of input will contain a single integer n (3 ≤ n ≤ 1 000) — the number of leaves in the tree.
Output
To print the final answer, print out the string "-1" on its own line. Then, the next line should contain 2n - 1 integers. The i-th integer should be the parent of the i-th node, or -1, if it is the root.
Your answer will be judged correct if your output is isomorphic to the judge's tree. In particular, the labels of the leaves do not need to be labeled from 1 to n. Here, isomorphic means that there exists a permutation π such that node i is the parent of node j in the judge tree if and only node π(i) is the parent of node π(j) in your tree.
Interaction
To ask a question, print out three distinct integers a1, a2, a3. These integers should be between 1 and n, inclusive.
The judge will respond with a single character, either "X", "Y", "Z".
If the string is "X" (or "Y", "Z" respectively), that means the pair (a1, a2) (or (a2, a3), (a3, a1) respectively) has the deepest LCA among the three pairs.
You may only ask a question at most 10·n times, otherwise, you will get Wrong Answer.
When you are ready to answer, print out a single integer "-1" on its own line. The next line should contain 2n - 1 integers. The i-th integer should be the parent of the i-th node, or -1, if it is the root. Do not forget to flush the final answer as well. Printing the answer does not count as asking a question.
You will get Wrong Answer verdict if
* Your question or answers are not in the format described in this statement.
* You ask strictly more than 10·n questions.
* Your question contains duplicate indices.
* Your final answer is not isomorphic to the judge tree.
You will get Idleness Limit Exceeded if you don't print anything or if you forget to flush the output, including for the final answer (more info about flushing output below).
To flush you can use (just after printing an integer and end-of-line):
* fflush(stdout) in C++;
* System.out.flush() in Java;
* stdout.flush() in Python;
* flush(output) in Pascal;
* See the documentation for other languages.
If at any moment your program reads -1 as an answer, it should immediately exit normally (for example, by calling exit(0)). You will get Wrong Answer in this case, it means that you made more queries than allowed, or made an invalid query. If you ignore this, you can get other verdicts since your program will continue to read from a closed stream.
Hacking To hack someone, use the following format
n
p_1 p_2 ... p_{2n-1}
This denotes a tree where the parent of the i-th node is pi (pi = - 1 or n < pi ≤ 2n - 1). If pi is equal to -1, then node i is the root. This input must describe a valid full rooted binary tree.
Of course, contestant programs will not be able to see this input.
Example
Input
5
X
Z
Y
Y
X<span class="tex-font-style-tt"></span>
Output
1 4 2
1 2 4
2 4 1
2 3 5
2 4 3
-1
-1 1 1 2 2 3 3 6 6
Note
For the first sample, the judge has the hidden tree:
<image>
Here is a more readable format of the interaction:
<image> The last line can also be 8 6 9 8 9 7 -1 6 7.
Submitted Solution:
```
from copy import copy
import sys
import random
def queryRaw(a, b, c):
print(a + 1, b + 1, c + 1, flush=True)
ans = " "
while ans not in "XYZ":
ans = sys.stdin.read(1)
if ans == "X":
bad = c
elif ans == "Y":
bad = a
else:
bad = b
return bad
queryCache = dict()
def query(a, b, c):
global queryCache
p = (a, b, c)
s = tuple(sorted(p))
if s in queryCache:
bad = queryCache[s]
else:
bad = queryRaw(a, b, c)
queryCache[s] = bad
if bad == a:
return (b, c)
elif bad == b:
return (c, a)
else:
return (a, b)
n = int(input())
root = [-1] * (2 * n)
cnt = -1
def findRoot(verts):
global cnt
if len(verts) == 1:
cnt += 1
return cnt
unused = list(verts)
random.shuffle(unused)
#print(unused)
a, b = (unused.pop() for i in range(2))
while unused:
c = unused.pop()
ans = query(a, b, c)
if ans == (a, b):
a, b = a, c
elif ans == (b, c):
a, b = a, b
else:
a, b = a, b
vA = set()
vB = set()
for c in verts:
if c == a:
vA.add(a)
elif c == b:
vB.add(b)
else:
ans = query(a, b, c)
if ans == (c, a):
vA.add(c)
else:
vB.add(c)
#print(vA, vB)
xa, xb = findRoot(vA), findRoot(vB)
cnt += 1
root[xa] = cnt
root[xb] = cnt
return cnt
smt = findRoot(set(range(n)))
print(-1)
print(*((x + 1) if x != -1 else -1 for x in root[:-1]))
``` | instruction | 0 | 80,500 | 13 | 161,000 |
No | output | 1 | 80,500 | 13 | 161,001 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
The judge has a hidden rooted full binary tree with n leaves. A full binary tree is one where every node has either 0 or 2 children. The nodes with 0 children are called the leaves of the tree. Since this is a full binary tree, there are exactly 2n - 1 nodes in the tree. The leaves of the judge's tree has labels from 1 to n. You would like to reconstruct a tree that is isomorphic to the judge's tree. To do this, you can ask some questions.
A question consists of printing the label of three distinct leaves a1, a2, a3. Let the depth of a node be the shortest distance from the node to the root of the tree. Let LCA(a, b) denote the node with maximum depth that is a common ancestor of the nodes a and b.
Consider X = LCA(a1, a2), Y = LCA(a2, a3), Z = LCA(a3, a1). The judge will tell you which one of X, Y, Z has the maximum depth. Note, this pair is uniquely determined since the tree is a binary tree; there can't be any ties.
More specifically, if X (or Y, Z respectively) maximizes the depth, the judge will respond with the string "X" (or "Y", "Z" respectively).
You may only ask at most 10·n questions.
Input
The first line of input will contain a single integer n (3 ≤ n ≤ 1 000) — the number of leaves in the tree.
Output
To print the final answer, print out the string "-1" on its own line. Then, the next line should contain 2n - 1 integers. The i-th integer should be the parent of the i-th node, or -1, if it is the root.
Your answer will be judged correct if your output is isomorphic to the judge's tree. In particular, the labels of the leaves do not need to be labeled from 1 to n. Here, isomorphic means that there exists a permutation π such that node i is the parent of node j in the judge tree if and only node π(i) is the parent of node π(j) in your tree.
Interaction
To ask a question, print out three distinct integers a1, a2, a3. These integers should be between 1 and n, inclusive.
The judge will respond with a single character, either "X", "Y", "Z".
If the string is "X" (or "Y", "Z" respectively), that means the pair (a1, a2) (or (a2, a3), (a3, a1) respectively) has the deepest LCA among the three pairs.
You may only ask a question at most 10·n times, otherwise, you will get Wrong Answer.
When you are ready to answer, print out a single integer "-1" on its own line. The next line should contain 2n - 1 integers. The i-th integer should be the parent of the i-th node, or -1, if it is the root. Do not forget to flush the final answer as well. Printing the answer does not count as asking a question.
You will get Wrong Answer verdict if
* Your question or answers are not in the format described in this statement.
* You ask strictly more than 10·n questions.
* Your question contains duplicate indices.
* Your final answer is not isomorphic to the judge tree.
You will get Idleness Limit Exceeded if you don't print anything or if you forget to flush the output, including for the final answer (more info about flushing output below).
To flush you can use (just after printing an integer and end-of-line):
* fflush(stdout) in C++;
* System.out.flush() in Java;
* stdout.flush() in Python;
* flush(output) in Pascal;
* See the documentation for other languages.
If at any moment your program reads -1 as an answer, it should immediately exit normally (for example, by calling exit(0)). You will get Wrong Answer in this case, it means that you made more queries than allowed, or made an invalid query. If you ignore this, you can get other verdicts since your program will continue to read from a closed stream.
Hacking To hack someone, use the following format
n
p_1 p_2 ... p_{2n-1}
This denotes a tree where the parent of the i-th node is pi (pi = - 1 or n < pi ≤ 2n - 1). If pi is equal to -1, then node i is the root. This input must describe a valid full rooted binary tree.
Of course, contestant programs will not be able to see this input.
Example
Input
5
X
Z
Y
Y
X<span class="tex-font-style-tt"></span>
Output
1 4 2
1 2 4
2 4 1
2 3 5
2 4 3
-1
-1 1 1 2 2 3 3 6 6
Note
For the first sample, the judge has the hidden tree:
<image>
Here is a more readable format of the interaction:
<image> The last line can also be 8 6 9 8 9 7 -1 6 7.
Submitted Solution:
```
'''from copy import copy
def queryRaw(a, b, c):
print(a + 1, b + 1, c + 1, flush=False)
ans = " "
while ans not in "XYZ":
ans = sys.stdin.read(1)
if ans == "X":
bad = c
elif ans == "Y":
bad = a
else:
bad = b
return bad
queryCache = dict()
def query(a, b, c):
global queryCache
p = (a, b, c)
s = tuple(sorted(p))
if s in queryCache:
bad = queryCache[s]
else:
bad = queryRaw(a, b, c)
queryCache[s] = bad
if bad == a:
return (b, c)
elif bad == b:
return (c, a)
else:
return (a, b)
n = int(input())
root = [-1] * (2 * n)
cnt = -1
def findRoot(verts):
global cnt
if len(verts) == 1:
cnt += 1
return cnt
unused = copy(verts)
#print(unused)
a = next(iter(unused))
unused.remove(a)
b = next(iter(unused))
unused.remove(b)
while unused:
c = next(iter(unused))
unused.remove(c)
ans = query(a, b, c)
if ans == (a, b):
a, b = a, c
elif ans == (b, c):
a, b = a, b
else:
a, b = a, b
vA = set()
vB = set()
for c in verts:
if c == a:
vA.add(a)
elif c == b:
vB.add(b)
else:
ans = query(a, b, c)
if ans == (c, a):
vA.add(c)
else:
vB.add(c)
#print(vA, vB)
xa, xb = findRoot(vA), findRoot(vB)
cnt += 1
root[xa] = cnt
root[xb] = cnt
return cnt
smt = findRoot(set(range(n)))
print(-1)
print(*((x + 1) if x != -1 else -1 for x in root[:-1]))'''
``` | instruction | 0 | 80,501 | 13 | 161,002 |
No | output | 1 | 80,501 | 13 | 161,003 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
The judge has a hidden rooted full binary tree with n leaves. A full binary tree is one where every node has either 0 or 2 children. The nodes with 0 children are called the leaves of the tree. Since this is a full binary tree, there are exactly 2n - 1 nodes in the tree. The leaves of the judge's tree has labels from 1 to n. You would like to reconstruct a tree that is isomorphic to the judge's tree. To do this, you can ask some questions.
A question consists of printing the label of three distinct leaves a1, a2, a3. Let the depth of a node be the shortest distance from the node to the root of the tree. Let LCA(a, b) denote the node with maximum depth that is a common ancestor of the nodes a and b.
Consider X = LCA(a1, a2), Y = LCA(a2, a3), Z = LCA(a3, a1). The judge will tell you which one of X, Y, Z has the maximum depth. Note, this pair is uniquely determined since the tree is a binary tree; there can't be any ties.
More specifically, if X (or Y, Z respectively) maximizes the depth, the judge will respond with the string "X" (or "Y", "Z" respectively).
You may only ask at most 10·n questions.
Input
The first line of input will contain a single integer n (3 ≤ n ≤ 1 000) — the number of leaves in the tree.
Output
To print the final answer, print out the string "-1" on its own line. Then, the next line should contain 2n - 1 integers. The i-th integer should be the parent of the i-th node, or -1, if it is the root.
Your answer will be judged correct if your output is isomorphic to the judge's tree. In particular, the labels of the leaves do not need to be labeled from 1 to n. Here, isomorphic means that there exists a permutation π such that node i is the parent of node j in the judge tree if and only node π(i) is the parent of node π(j) in your tree.
Interaction
To ask a question, print out three distinct integers a1, a2, a3. These integers should be between 1 and n, inclusive.
The judge will respond with a single character, either "X", "Y", "Z".
If the string is "X" (or "Y", "Z" respectively), that means the pair (a1, a2) (or (a2, a3), (a3, a1) respectively) has the deepest LCA among the three pairs.
You may only ask a question at most 10·n times, otherwise, you will get Wrong Answer.
When you are ready to answer, print out a single integer "-1" on its own line. The next line should contain 2n - 1 integers. The i-th integer should be the parent of the i-th node, or -1, if it is the root. Do not forget to flush the final answer as well. Printing the answer does not count as asking a question.
You will get Wrong Answer verdict if
* Your question or answers are not in the format described in this statement.
* You ask strictly more than 10·n questions.
* Your question contains duplicate indices.
* Your final answer is not isomorphic to the judge tree.
You will get Idleness Limit Exceeded if you don't print anything or if you forget to flush the output, including for the final answer (more info about flushing output below).
To flush you can use (just after printing an integer and end-of-line):
* fflush(stdout) in C++;
* System.out.flush() in Java;
* stdout.flush() in Python;
* flush(output) in Pascal;
* See the documentation for other languages.
If at any moment your program reads -1 as an answer, it should immediately exit normally (for example, by calling exit(0)). You will get Wrong Answer in this case, it means that you made more queries than allowed, or made an invalid query. If you ignore this, you can get other verdicts since your program will continue to read from a closed stream.
Hacking To hack someone, use the following format
n
p_1 p_2 ... p_{2n-1}
This denotes a tree where the parent of the i-th node is pi (pi = - 1 or n < pi ≤ 2n - 1). If pi is equal to -1, then node i is the root. This input must describe a valid full rooted binary tree.
Of course, contestant programs will not be able to see this input.
Example
Input
5
X
Z
Y
Y
X<span class="tex-font-style-tt"></span>
Output
1 4 2
1 2 4
2 4 1
2 3 5
2 4 3
-1
-1 1 1 2 2 3 3 6 6
Note
For the first sample, the judge has the hidden tree:
<image>
Here is a more readable format of the interaction:
<image> The last line can also be 8 6 9 8 9 7 -1 6 7.
Submitted Solution:
```
from copy import copy
import sys
import random
random.shuffle([1, 3, 2])
def queryRaw(a, b, c):
print(a + 1, b + 1, c + 1, flush=True)
ans = " "
while ans not in "XYZ":
ans = sys.stdin.read(1)
if ans == "X":
bad = c
elif ans == "Y":
bad = a
else:
bad = b
return bad
queryCache = dict()
def query(a, b, c):
global queryCache
p = (a, b, c)
s = tuple(sorted(p))
if s in queryCache:
bad = queryCache[s]
else:
bad = queryRaw(a, b, c)
queryCache[s] = bad
if bad == a:
return (b, c)
elif bad == b:
return (c, a)
else:
return (a, b)
n = int(input())
root = [-1] * (2 * n)
cnt = -1
def findRoot(verts):
global cnt
if len(verts) == 1:
cnt += 1
return cnt
unused = list(verts)
random.shuffle(unused)
#print(unused)
a, b = (unused.pop() for i in range(2))
while unused:
c = unused.pop()
ans = query(a, b, c)
if ans == (a, b):
a, b = a, c
elif ans == (b, c):
a, b = a, b
else:
a, b = a, b
vA = set()
vB = set()
for c in verts:
if c == a:
vA.add(a)
elif c == b:
vB.add(b)
else:
ans = query(a, b, c)
if ans == (c, a):
vA.add(c)
else:
vB.add(c)
#print(vA, vB)
xa, xb = findRoot(vA), findRoot(vB)
cnt += 1
root[xa] = cnt
root[xb] = cnt
return cnt
smt = findRoot(set(range(n)))
print(-1)
print(*((x + 1) if x != -1 else -1 for x in root[:-1]))
``` | instruction | 0 | 80,502 | 13 | 161,004 |
No | output | 1 | 80,502 | 13 | 161,005 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
The judge has a hidden rooted full binary tree with n leaves. A full binary tree is one where every node has either 0 or 2 children. The nodes with 0 children are called the leaves of the tree. Since this is a full binary tree, there are exactly 2n - 1 nodes in the tree. The leaves of the judge's tree has labels from 1 to n. You would like to reconstruct a tree that is isomorphic to the judge's tree. To do this, you can ask some questions.
A question consists of printing the label of three distinct leaves a1, a2, a3. Let the depth of a node be the shortest distance from the node to the root of the tree. Let LCA(a, b) denote the node with maximum depth that is a common ancestor of the nodes a and b.
Consider X = LCA(a1, a2), Y = LCA(a2, a3), Z = LCA(a3, a1). The judge will tell you which one of X, Y, Z has the maximum depth. Note, this pair is uniquely determined since the tree is a binary tree; there can't be any ties.
More specifically, if X (or Y, Z respectively) maximizes the depth, the judge will respond with the string "X" (or "Y", "Z" respectively).
You may only ask at most 10·n questions.
Input
The first line of input will contain a single integer n (3 ≤ n ≤ 1 000) — the number of leaves in the tree.
Output
To print the final answer, print out the string "-1" on its own line. Then, the next line should contain 2n - 1 integers. The i-th integer should be the parent of the i-th node, or -1, if it is the root.
Your answer will be judged correct if your output is isomorphic to the judge's tree. In particular, the labels of the leaves do not need to be labeled from 1 to n. Here, isomorphic means that there exists a permutation π such that node i is the parent of node j in the judge tree if and only node π(i) is the parent of node π(j) in your tree.
Interaction
To ask a question, print out three distinct integers a1, a2, a3. These integers should be between 1 and n, inclusive.
The judge will respond with a single character, either "X", "Y", "Z".
If the string is "X" (or "Y", "Z" respectively), that means the pair (a1, a2) (or (a2, a3), (a3, a1) respectively) has the deepest LCA among the three pairs.
You may only ask a question at most 10·n times, otherwise, you will get Wrong Answer.
When you are ready to answer, print out a single integer "-1" on its own line. The next line should contain 2n - 1 integers. The i-th integer should be the parent of the i-th node, or -1, if it is the root. Do not forget to flush the final answer as well. Printing the answer does not count as asking a question.
You will get Wrong Answer verdict if
* Your question or answers are not in the format described in this statement.
* You ask strictly more than 10·n questions.
* Your question contains duplicate indices.
* Your final answer is not isomorphic to the judge tree.
You will get Idleness Limit Exceeded if you don't print anything or if you forget to flush the output, including for the final answer (more info about flushing output below).
To flush you can use (just after printing an integer and end-of-line):
* fflush(stdout) in C++;
* System.out.flush() in Java;
* stdout.flush() in Python;
* flush(output) in Pascal;
* See the documentation for other languages.
If at any moment your program reads -1 as an answer, it should immediately exit normally (for example, by calling exit(0)). You will get Wrong Answer in this case, it means that you made more queries than allowed, or made an invalid query. If you ignore this, you can get other verdicts since your program will continue to read from a closed stream.
Hacking To hack someone, use the following format
n
p_1 p_2 ... p_{2n-1}
This denotes a tree where the parent of the i-th node is pi (pi = - 1 or n < pi ≤ 2n - 1). If pi is equal to -1, then node i is the root. This input must describe a valid full rooted binary tree.
Of course, contestant programs will not be able to see this input.
Example
Input
5
X
Z
Y
Y
X<span class="tex-font-style-tt"></span>
Output
1 4 2
1 2 4
2 4 1
2 3 5
2 4 3
-1
-1 1 1 2 2 3 3 6 6
Note
For the first sample, the judge has the hidden tree:
<image>
Here is a more readable format of the interaction:
<image> The last line can also be 8 6 9 8 9 7 -1 6 7.
Submitted Solution:
```
import sys
from copy import copy
def queryRaw(a, b, c):
print(a + 1, b + 1, c + 1, flush=True)
ans = " "
while ans not in "XYZ":
ans = sys.stdin.read(1)
if ans == "X":
bad = c
elif ans == "Y":
bad = a
else:
bad = b
return bad
queryCache = dict()
def query(a, b, c):
global queryCache
p = (a, b, c)
s = tuple(sorted(p))
if s in queryCache:
bad = queryCache[s]
else:
bad = queryRaw(a, b, c)
queryCache[s] = bad
if bad == a:
return (b, c)
elif bad == b:
return (c, a)
else:
return (a, b)
n = int(input())
root = [-1] * (2 * n)
cnt = -1
def findRoot(verts):
global cnt
if len(verts) == 1:
cnt += 1
return cnt
unused = copy(verts)
#print(unused)
a = next(iter(unused))
unused.remove(a)
b = next(iter(unused))
unused.remove(b)
while unused:
c = next(iter(unused))
unused.remove(c)
ans = query(a, b, c)
if ans == (a, b):
a, b = a, c
elif ans == (b, c):
a, b = a, b
else:
a, b = a, b
vA = set()
vB = set()
for c in verts:
if c == a:
vA.add(a)
elif c == b:
vB.add(b)
else:
ans = query(a, b, c)
if ans == (c, a):
vA.add(c)
else:
vB.add(c)
#print(vA, vB)
xa, xb = findRoot(vA), findRoot(vB)
cnt += 1
root[xa] = cnt
root[xb] = cnt
return cnt
smt = findRoot(set(range(n)))
print(-1)
print(*((x + 1) if x != -1 else -1 for x in root[:-1]))
``` | instruction | 0 | 80,503 | 13 | 161,006 |
No | output | 1 | 80,503 | 13 | 161,007 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a full binary tree having infinite levels.
Each node has an initial value. If a node has value x, then its left child has value 2·x and its right child has value 2·x + 1.
The value of the root is 1.
You need to answer Q queries.
There are 3 types of queries:
1. Cyclically shift the values of all nodes on the same level as node with value X by K units. (The values/nodes of any other level are not affected).
2. Cyclically shift the nodes on the same level as node with value X by K units. (The subtrees of these nodes will move along with them).
3. Print the value of every node encountered on the simple path from the node with value X to the root.
Positive K implies right cyclic shift and negative K implies left cyclic shift.
It is guaranteed that atleast one type 3 query is present.
Input
The first line contains a single integer Q (1 ≤ Q ≤ 105).
Then Q queries follow, one per line:
* Queries of type 1 and 2 have the following format: T X K (1 ≤ T ≤ 2; 1 ≤ X ≤ 1018; 0 ≤ |K| ≤ 1018), where T is type of the query.
* Queries of type 3 have the following format: 3 X (1 ≤ X ≤ 1018).
Output
For each query of type 3, print the values of all nodes encountered in descending order.
Examples
Input
5
3 12
1 2 1
3 12
2 4 -1
3 8
Output
12 6 3 1
12 6 2 1
8 4 2 1
Input
5
3 14
1 5 -3
3 14
1 3 1
3 14
Output
14 7 3 1
14 6 3 1
14 6 2 1
Note
Following are the images of the first 4 levels of the tree in the first test case:
Original:
<image>
After query 1 2 1:
<image>
After query 2 4 -1:
<image>
Submitted Solution:
```
q = int(input())
op1 = [0 for x in range(100)]
def pw(n,k):
s = 1
for x in range(k):
s *= n
return int(s)
def getlvl(X):
start = 1
end = 2
level = 0
while not (start <= X and X < end):
start *= 2
end *= 2
level += 1
return level
def mod(n,m):
return (n+m*10**18)%m
for test in range(q):
A = [int(x) for x in input().split()]
if A[0] <= 2:
begin = getlvl(A[1])
to = 100
if A[0] == 1:
to = begin+1
for x in range(begin,to):
op1[x] += A[2]
op1[x] += abs(A[2])*10**18
op1[x] %= 10**18
A[2] *= 2;
else:
level = getlvl(A[1])
arr = []
at = A[1]
at -= pw(2,level)
at = mod(at+op1[level], pw(2,level))
at += pw(2,level)
arr.append(str(A[1]))
while level != 0:
old = at
at //= 2
level -= 1
at -= pw(2,level)
at = mod(at-op1[level], pw(2,level))
at += pw(2,level)
arr.append(str(at))
at = old // 2
print(" ".join(arr))
``` | instruction | 0 | 80,582 | 13 | 161,164 |
No | output | 1 | 80,582 | 13 | 161,165 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a full binary tree having infinite levels.
Each node has an initial value. If a node has value x, then its left child has value 2·x and its right child has value 2·x + 1.
The value of the root is 1.
You need to answer Q queries.
There are 3 types of queries:
1. Cyclically shift the values of all nodes on the same level as node with value X by K units. (The values/nodes of any other level are not affected).
2. Cyclically shift the nodes on the same level as node with value X by K units. (The subtrees of these nodes will move along with them).
3. Print the value of every node encountered on the simple path from the node with value X to the root.
Positive K implies right cyclic shift and negative K implies left cyclic shift.
It is guaranteed that atleast one type 3 query is present.
Input
The first line contains a single integer Q (1 ≤ Q ≤ 105).
Then Q queries follow, one per line:
* Queries of type 1 and 2 have the following format: T X K (1 ≤ T ≤ 2; 1 ≤ X ≤ 1018; 0 ≤ |K| ≤ 1018), where T is type of the query.
* Queries of type 3 have the following format: 3 X (1 ≤ X ≤ 1018).
Output
For each query of type 3, print the values of all nodes encountered in descending order.
Examples
Input
5
3 12
1 2 1
3 12
2 4 -1
3 8
Output
12 6 3 1
12 6 2 1
8 4 2 1
Input
5
3 14
1 5 -3
3 14
1 3 1
3 14
Output
14 7 3 1
14 6 3 1
14 6 2 1
Note
Following are the images of the first 4 levels of the tree in the first test case:
Original:
<image>
After query 1 2 1:
<image>
After query 2 4 -1:
<image>
Submitted Solution:
```
q = int(input())
op1 = [0 for x in range(100)]
def pw(n,k):
s = 1
for x in range(k):
s *= n
return int(s)
def getlvl(X):
start = 1
end = 2
level = 0
while not (start <= X and X < end):
start *= 2
end *= 2
level += 1
return level
def mod(n,m):
return n%m
for test in range(q):
A = [int(x) for x in input().split()]
if A[0] <= 2:
begin = getlvl(A[1])
to = 100
if A[0] == 1:
to = begin+1
for x in range(begin,to):
op1[x] += A[2]
op1[x] += abs(A[2])*10**18
op1[x] %= 10**18
A[2] *= 2;
else:
level = getlvl(A[1])
arr = []
at = A[1]
at -= pw(2,level)
at = mod(at+op1[level], pw(2,level))
at += pw(2,level)
arr.append(str(A[1]))
while level != 0:
old = at
at //= 2
level -= 1
at -= pw(2,level)
at = mod(at-op1[level], pw(2,level))
at += pw(2,level)
arr.append(str(at))
at = old // 2
print(" ".join(arr))
``` | instruction | 0 | 80,583 | 13 | 161,166 |
No | output | 1 | 80,583 | 13 | 161,167 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a full binary tree having infinite levels.
Each node has an initial value. If a node has value x, then its left child has value 2·x and its right child has value 2·x + 1.
The value of the root is 1.
You need to answer Q queries.
There are 3 types of queries:
1. Cyclically shift the values of all nodes on the same level as node with value X by K units. (The values/nodes of any other level are not affected).
2. Cyclically shift the nodes on the same level as node with value X by K units. (The subtrees of these nodes will move along with them).
3. Print the value of every node encountered on the simple path from the node with value X to the root.
Positive K implies right cyclic shift and negative K implies left cyclic shift.
It is guaranteed that atleast one type 3 query is present.
Input
The first line contains a single integer Q (1 ≤ Q ≤ 105).
Then Q queries follow, one per line:
* Queries of type 1 and 2 have the following format: T X K (1 ≤ T ≤ 2; 1 ≤ X ≤ 1018; 0 ≤ |K| ≤ 1018), where T is type of the query.
* Queries of type 3 have the following format: 3 X (1 ≤ X ≤ 1018).
Output
For each query of type 3, print the values of all nodes encountered in descending order.
Examples
Input
5
3 12
1 2 1
3 12
2 4 -1
3 8
Output
12 6 3 1
12 6 2 1
8 4 2 1
Input
5
3 14
1 5 -3
3 14
1 3 1
3 14
Output
14 7 3 1
14 6 3 1
14 6 2 1
Note
Following are the images of the first 4 levels of the tree in the first test case:
Original:
<image>
After query 1 2 1:
<image>
After query 2 4 -1:
<image>
Submitted Solution:
```
def lg(x):
s=0
while x>0:
x//=2
s+=1
return s
rot1 = {}
rot2 = {}
def f1(s):
_,x,k=map(int, s.split())
lvl=lg(x)
if lvl in rot1:
rot1[lvl]+=k
else:
rot1[lvl]=k
def f2(s):
_, x, k =map(int,s.split())
lvl=lg(x)
if lvl in rot2:
rot2[lvl]+=k
else:
rot2[lvl]=k
def pr_path(x, first=False):
q=x
lvl=lg(x)
min_val=2**(lvl-1)
if first:
print(q, end=' ')
if lvl==1:
print(1)
return
rot = rot2.get(lvl-1,0)*2+rot1.get(lvl,0)+rot2.get(lvl,0)
rot%=min_val
if rot<0:
rot+=min_val
if first:
x+=rot
else:
x-=rot
if x<min_val:
x+=min_val
if x>=2*min_val:
x-=min_val
if not first:
print(x, end=' ')
if first:
q=x
pr_path(q//2)
def f3(s):
x=int(s.split()[1])
pr_path(x,True)
q=int(input())
for _ in range(q):
s=input()
if s[0]=='1':
f1(s)
elif s[0]=='2':
f2(s)
else:
f3(s)
``` | instruction | 0 | 80,584 | 13 | 161,168 |
No | output | 1 | 80,584 | 13 | 161,169 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a full binary tree having infinite levels.
Each node has an initial value. If a node has value x, then its left child has value 2·x and its right child has value 2·x + 1.
The value of the root is 1.
You need to answer Q queries.
There are 3 types of queries:
1. Cyclically shift the values of all nodes on the same level as node with value X by K units. (The values/nodes of any other level are not affected).
2. Cyclically shift the nodes on the same level as node with value X by K units. (The subtrees of these nodes will move along with them).
3. Print the value of every node encountered on the simple path from the node with value X to the root.
Positive K implies right cyclic shift and negative K implies left cyclic shift.
It is guaranteed that atleast one type 3 query is present.
Input
The first line contains a single integer Q (1 ≤ Q ≤ 105).
Then Q queries follow, one per line:
* Queries of type 1 and 2 have the following format: T X K (1 ≤ T ≤ 2; 1 ≤ X ≤ 1018; 0 ≤ |K| ≤ 1018), where T is type of the query.
* Queries of type 3 have the following format: 3 X (1 ≤ X ≤ 1018).
Output
For each query of type 3, print the values of all nodes encountered in descending order.
Examples
Input
5
3 12
1 2 1
3 12
2 4 -1
3 8
Output
12 6 3 1
12 6 2 1
8 4 2 1
Input
5
3 14
1 5 -3
3 14
1 3 1
3 14
Output
14 7 3 1
14 6 3 1
14 6 2 1
Note
Following are the images of the first 4 levels of the tree in the first test case:
Original:
<image>
After query 1 2 1:
<image>
After query 2 4 -1:
<image>
Submitted Solution:
```
def lg(x):
s=0
while x>0:
x//=2
s+=1
return s
rot1 = {}
rot2 = {}
def f1(s):
_,x,k=map(int, s.split())
lvl=lg(x)
if lvl in rot1:
rot1[lvl]+=k
else:
rot1[lvl]=k
def f2(s):
_, x, k =map(int,s.split())
lvl=lg(x)
if lvl in rot2:
rot2[lvl]+=k
else:
rot2[lvl]=k
def pr_path(x, first=False):
q=x
lvl=lg(x)
min_val=2**(lvl-1)
if lvl==1:
print(1)
return
if first:
print(q, end=' ')
rot = rot2.get(lvl-1,0)*2+rot1.get(lvl,0)+rot2.get(lvl,0)
rot%=min_val
if rot<0:
rot+=min_val
if first:
x+=rot
else:
x-=rot
if x<min_val:
x+=min_val
if x>=2*min_val:
x-=min_val
if not first:
print(x, end=' ')
if first:
q=x
pr_path(q//2)
def f3(s):
x=int(s.split()[1])
pr_path(x,True)
q=int(input())
for _ in range(q):
s=input()
if s[0]=='1':
f1(s)
elif s[0]=='2':
f2(s)
else:
f3(s)
``` | instruction | 0 | 80,585 | 13 | 161,170 |
No | output | 1 | 80,585 | 13 | 161,171 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G. G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.
First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing.
Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa.
Constraints
* 2 \leq N \leq 10^5
* 0 \leq M \leq \min(10^5, N (N-1))
* 1 \leq u_i, v_i \leq N(1 \leq i \leq M)
* u_i \neq v_i (1 \leq i \leq M)
* If i \neq j, (u_i, v_i) \neq (u_j, v_j).
* 1 \leq S, T \leq N
* S \neq T
Input
Input is given from Standard Input in the following format:
N M
u_1 v_1
:
u_M v_M
S T
Output
If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1. If he can, print the minimum number of ken-ken-pa needed to reach vertex T.
Examples
Input
4 4
1 2
2 3
3 4
4 1
1 3
Output
2
Input
3 3
1 2
2 3
3 1
1 2
Output
-1
Input
2 0
1 2
Output
-1
Input
6 8
1 2
2 3
3 4
4 5
5 1
1 4
1 5
4 6
1 6
Output
2
Submitted Solution:
```
import sys
from collections import defaultdict, deque
input = sys.stdin.readline
N,M= map(int,input().split())
g = defaultdict(list)
for i in range(M):
u,v = list(map(int,input().split()))
g[u].append(N + v)
g[N + u].append(2*N + v)
g[2*N + u].append(v)
S,T= map(int,input().split())
dq = deque([S])
inf = 10**15
d = [inf for i in range(3*N+1)]
d[S] = 0
while dq:
v = dq.popleft()
for nv in g[v]:
if d[nv] > d[v] + 1:
d[nv] = d[v] + 1
dq.append(nv)
if inf == d[T]:
print(-1)
else:
print(d[T]//3)
``` | instruction | 0 | 80,646 | 13 | 161,292 |
Yes | output | 1 | 80,646 | 13 | 161,293 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G. G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.
First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing.
Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa.
Constraints
* 2 \leq N \leq 10^5
* 0 \leq M \leq \min(10^5, N (N-1))
* 1 \leq u_i, v_i \leq N(1 \leq i \leq M)
* u_i \neq v_i (1 \leq i \leq M)
* If i \neq j, (u_i, v_i) \neq (u_j, v_j).
* 1 \leq S, T \leq N
* S \neq T
Input
Input is given from Standard Input in the following format:
N M
u_1 v_1
:
u_M v_M
S T
Output
If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1. If he can, print the minimum number of ken-ken-pa needed to reach vertex T.
Examples
Input
4 4
1 2
2 3
3 4
4 1
1 3
Output
2
Input
3 3
1 2
2 3
3 1
1 2
Output
-1
Input
2 0
1 2
Output
-1
Input
6 8
1 2
2 3
3 4
4 5
5 1
1 4
1 5
4 6
1 6
Output
2
Submitted Solution:
```
from collections import deque
n,m=map(int,input().split())
g=[[] for _ in range(n)]
for _ in range(m):
u,v=list(map(int,input().split()))
g[u-1].append(v-1)
S,T=map(int,input().split())
S-=1;T-=1
INF=10**9
U=[[INF]*n for i in range(3)]
U[0][S]=0
que=deque([(0,S)])
while que:
t,v=que.popleft()
u=(t+1)%3
if t==2:
U[t][v]+=1
for w in g[v]:
if U[u][w]!=INF:
continue
que.append((u,w))
U[u][w]=U[t][v]
print(U[0][T] if U[0][T]<INF else -1)
``` | instruction | 0 | 80,647 | 13 | 161,294 |
Yes | output | 1 | 80,647 | 13 | 161,295 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G. G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.
First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing.
Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa.
Constraints
* 2 \leq N \leq 10^5
* 0 \leq M \leq \min(10^5, N (N-1))
* 1 \leq u_i, v_i \leq N(1 \leq i \leq M)
* u_i \neq v_i (1 \leq i \leq M)
* If i \neq j, (u_i, v_i) \neq (u_j, v_j).
* 1 \leq S, T \leq N
* S \neq T
Input
Input is given from Standard Input in the following format:
N M
u_1 v_1
:
u_M v_M
S T
Output
If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1. If he can, print the minimum number of ken-ken-pa needed to reach vertex T.
Examples
Input
4 4
1 2
2 3
3 4
4 1
1 3
Output
2
Input
3 3
1 2
2 3
3 1
1 2
Output
-1
Input
2 0
1 2
Output
-1
Input
6 8
1 2
2 3
3 4
4 5
5 1
1 4
1 5
4 6
1 6
Output
2
Submitted Solution:
```
from collections import deque
# 木構造を作る
N,M = map(int, input().split())
G = [[] for i in range(3*N)]
for i in range(M):
# グラフに頂点を追加(距離があるときは,u,vの後に入れる)
u,v = map(int,input().split())
G[3*(u-1)].append((3*(v-1)+1))
G[3*(u-1)+1].append((3*(v-1)+2))
G[3*(u-1)+2].append((3*(v-1)))
S,T = map(int, input().split())
# 木をBFSをする
dist = [-1] * (3*N)
dist[3*(S-1)] = 0
q = deque([3*(S-1)])
while q:
v = q.popleft()
d = dist[v]
Vs = G[v]
for u in Vs:
if dist[u] == -1:
q.append(u)
dist[u] = d + 1
ans = dist[3*(T-1)]
print(-1 if ans == -1 else ans//3)
``` | instruction | 0 | 80,648 | 13 | 161,296 |
Yes | output | 1 | 80,648 | 13 | 161,297 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G. G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.
First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing.
Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa.
Constraints
* 2 \leq N \leq 10^5
* 0 \leq M \leq \min(10^5, N (N-1))
* 1 \leq u_i, v_i \leq N(1 \leq i \leq M)
* u_i \neq v_i (1 \leq i \leq M)
* If i \neq j, (u_i, v_i) \neq (u_j, v_j).
* 1 \leq S, T \leq N
* S \neq T
Input
Input is given from Standard Input in the following format:
N M
u_1 v_1
:
u_M v_M
S T
Output
If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1. If he can, print the minimum number of ken-ken-pa needed to reach vertex T.
Examples
Input
4 4
1 2
2 3
3 4
4 1
1 3
Output
2
Input
3 3
1 2
2 3
3 1
1 2
Output
-1
Input
2 0
1 2
Output
-1
Input
6 8
1 2
2 3
3 4
4 5
5 1
1 4
1 5
4 6
1 6
Output
2
Submitted Solution:
```
N, M = map(int, input().split())
nodes = [[] for i in range(N)]
for i in range(M):
u, v = map(int, input().split())
u -= 1
v -= 1
nodes[u].append(v)
s, t = map(int, input().split())
s -= 1
t -= 1
num = s
step = 0
q = [[num, step]]
check = [[False for i in range(N)] for j in range(3)]
ok = False
while len(q) > 0:
num, step = q.pop(0)
tmp = step % 3
if tmp == 0 and num == t:
print(step//3)
ok = True
break
for next in nodes[num]:
if not check[tmp][next]:
check[tmp][next] = True
q.append([next, step+1])
if not ok:
print(-1)
``` | instruction | 0 | 80,649 | 13 | 161,298 |
Yes | output | 1 | 80,649 | 13 | 161,299 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G. G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.
First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing.
Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa.
Constraints
* 2 \leq N \leq 10^5
* 0 \leq M \leq \min(10^5, N (N-1))
* 1 \leq u_i, v_i \leq N(1 \leq i \leq M)
* u_i \neq v_i (1 \leq i \leq M)
* If i \neq j, (u_i, v_i) \neq (u_j, v_j).
* 1 \leq S, T \leq N
* S \neq T
Input
Input is given from Standard Input in the following format:
N M
u_1 v_1
:
u_M v_M
S T
Output
If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1. If he can, print the minimum number of ken-ken-pa needed to reach vertex T.
Examples
Input
4 4
1 2
2 3
3 4
4 1
1 3
Output
2
Input
3 3
1 2
2 3
3 1
1 2
Output
-1
Input
2 0
1 2
Output
-1
Input
6 8
1 2
2 3
3 4
4 5
5 1
1 4
1 5
4 6
1 6
Output
2
Submitted Solution:
```
def BC132_E():
n, m = list(map(int, input().split(' ')))
e = [[] for _ in range(n)]
for _ in range(m):
u, v = list(map(int, input().split(' ')))
e[u - 1].append(v - 1)
s, t = list(map(int, input().split(' ')))
s, t = s - 1, t - 1
stack, visited = [(s, 0)], set()
while stack:
i, d = stack.pop(0)
if i == t: return d
if i in visited:
continue
visited.add(i)
a = set()
for j in e[i]:
a.update(e[j])
b = set()
for j in list(a):
b.update(e[j])
stack += [(x, d + 1) for x in list(b - visited)]
return -1
print(BC132_E())
``` | instruction | 0 | 80,650 | 13 | 161,300 |
No | output | 1 | 80,650 | 13 | 161,301 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G. G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.
First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing.
Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa.
Constraints
* 2 \leq N \leq 10^5
* 0 \leq M \leq \min(10^5, N (N-1))
* 1 \leq u_i, v_i \leq N(1 \leq i \leq M)
* u_i \neq v_i (1 \leq i \leq M)
* If i \neq j, (u_i, v_i) \neq (u_j, v_j).
* 1 \leq S, T \leq N
* S \neq T
Input
Input is given from Standard Input in the following format:
N M
u_1 v_1
:
u_M v_M
S T
Output
If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1. If he can, print the minimum number of ken-ken-pa needed to reach vertex T.
Examples
Input
4 4
1 2
2 3
3 4
4 1
1 3
Output
2
Input
3 3
1 2
2 3
3 1
1 2
Output
-1
Input
2 0
1 2
Output
-1
Input
6 8
1 2
2 3
3 4
4 5
5 1
1 4
1 5
4 6
1 6
Output
2
Submitted Solution:
```
import sys
input = sys.stdin.readline
from collections import deque
def solve():
n,m = (int(i) for i in input().split())
step = [[] for _ in range(n)]
for i in range(m):
u,v = (int(i) for i in input().split())
if not v in step[u-1]:
step[u-1].append(v)
S,T = (int(i) for i in input().split())
query = deque([])
query.append((S,0))
visit = [False for _ in range(n+2)]
ans = 5000000
checker = 0
time = 0
while query:
time += 1
place,move = query.popleft()
move += 1
if move%3 ==0 and visit[place]:
continue
else:
if move%3 == 0:
visit[place] = True
for i in range(len(step[place-1])):
query.append((step[place-1][i],move))
if place == T and (move-1)%3 == 0:
ans = min(ans,move-1)
break
if time >= 500000:
break
if not ans == 5000000:
print(ans//3)
else:
print(-1)
solve()
``` | instruction | 0 | 80,651 | 13 | 161,302 |
No | output | 1 | 80,651 | 13 | 161,303 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G. G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.
First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing.
Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa.
Constraints
* 2 \leq N \leq 10^5
* 0 \leq M \leq \min(10^5, N (N-1))
* 1 \leq u_i, v_i \leq N(1 \leq i \leq M)
* u_i \neq v_i (1 \leq i \leq M)
* If i \neq j, (u_i, v_i) \neq (u_j, v_j).
* 1 \leq S, T \leq N
* S \neq T
Input
Input is given from Standard Input in the following format:
N M
u_1 v_1
:
u_M v_M
S T
Output
If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1. If he can, print the minimum number of ken-ken-pa needed to reach vertex T.
Examples
Input
4 4
1 2
2 3
3 4
4 1
1 3
Output
2
Input
3 3
1 2
2 3
3 1
1 2
Output
-1
Input
2 0
1 2
Output
-1
Input
6 8
1 2
2 3
3 4
4 5
5 1
1 4
1 5
4 6
1 6
Output
2
Submitted Solution:
```
from collections import defaultdict
from queue import Queue
n, m = list(map(int, input().split()))
MX = int(1e6)
edge = defaultdict(set)
kenedge = defaultdict(set)
dist = [MX for i in range(n)]
reached = [False for i in range(n)]
for loop in range(m):
a, b = list(map(int, input().split()))
edge[a-1].add(b-1)
for i in range(n):
step1 = set()
for ii in edge[i]:
step1 |= edge[ii]
step2 = set()
for iii in step1:
step2 |= edge[iii]
step3 = set()
for iiii in step2:
kenedge[i].add(iiii)
s, t = list(map(int, input().split()))
s = s-1
t = t-1
dist[s] = 0
q = Queue()
q.put(s)
reached[s] = True
while not q.empty():
node = q.get()
for next_node in kenedge[node]:
if reached[next_node]: continue
reached[next_node] = True
q.put(next_node)
dist[next_node] = min(dist[next_node], dist[node] + 1)
if dist[t] == MX:
print(-1)
else:
print(dist[t])
``` | instruction | 0 | 80,652 | 13 | 161,304 |
No | output | 1 | 80,652 | 13 | 161,305 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G. G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.
First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing.
Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa.
Constraints
* 2 \leq N \leq 10^5
* 0 \leq M \leq \min(10^5, N (N-1))
* 1 \leq u_i, v_i \leq N(1 \leq i \leq M)
* u_i \neq v_i (1 \leq i \leq M)
* If i \neq j, (u_i, v_i) \neq (u_j, v_j).
* 1 \leq S, T \leq N
* S \neq T
Input
Input is given from Standard Input in the following format:
N M
u_1 v_1
:
u_M v_M
S T
Output
If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1. If he can, print the minimum number of ken-ken-pa needed to reach vertex T.
Examples
Input
4 4
1 2
2 3
3 4
4 1
1 3
Output
2
Input
3 3
1 2
2 3
3 1
1 2
Output
-1
Input
2 0
1 2
Output
-1
Input
6 8
1 2
2 3
3 4
4 5
5 1
1 4
1 5
4 6
1 6
Output
2
Submitted Solution:
```
N, M = map(int, input().split())
from collections import defaultdict
graph = defaultdict(list)
for i in range(M):
u, v = map(int, input().split())
u -= 1
v -= 1
graph[u].append(v + N)
graph[u + N].append(v + 2 * N)
graph[u + 2 * N].append(v)
S, T = map(int, input().split())
S -= 1
T -= 1
cnt = 3 * N + 4
dist = [float("inf")] * cnt
que = [S]
dist[S] = 0
visited = [False] * cnt
visited[S] = True
while len(que) != 0:
q = que.pop()
for v in graph[q]:
if v == q:
continue
if dist[v] > dist[q] + 1:
dist[v] = dist[q] + 1
visited[v] = True
que.append(v)
if dist[T] % 3 == 0:
print(dist[T] // 3)
else:
print(-1)
``` | instruction | 0 | 80,653 | 13 | 161,306 |
No | output | 1 | 80,653 | 13 | 161,307 |
Provide a correct Python 3 solution for this coding contest problem.
H --Bit Operation Game
Given a rooted tree with N vertices. The vertices are numbered from 0 to N − 1, and the 0th vertex represents the root. `T = 0` for the root, but for the other vertices
* `T = T & X;`
* `T = T & Y;`
* `T = T | X`
* `T = T | Y`
* `T = T ^ X`
* `T = T ^ Y`
One of the operations is written. Here, the operators &, |, ^ mean the bitwise operators and, or, xor, respectively.
Mr. A and Mr. B played the following games M times using this tree. The two start from the root and select the child vertices and proceed alternately, starting from Mr. A and reaching the leaves. The final T value when the operations written in the passed nodes are applied in the order of passing is the score. Mr. B wants to make the score as small as possible, and Mr. A wants to make it large. Given the X and Y values of the M games, output the score for each game when the two make the best choice.
Constraints
* 1 ≤ N ≤ 100000
* 1 ≤ M ≤ 100000
* 0 ≤ X, Y <2 ^ {16}
Input Format
Input is given from standard input in the following format.
N M
o_1_1
o_2
...
o_ {N−1}
u_1 v_1
u_2 v_2
...
u_ {N−1} v_ {N−1}
X_1 Y_1
X_2 Y_2
...
X_M Y_M
On the first line, the number of vertices N of the tree and the integer M representing the number of games played are entered.
From the 2nd line to the Nth line, the operation written at the 1st ... N-1st vertex is input.
In addition, the numbers of the two vertices connected by each side are entered in the N-1 line.
Finally, the values of X and Y in M games are entered over M lines.
Output Format
Print the final T value for each game on the M line.
Sample Input 1
6 3
T = T | X
T = T | Y
T = T | Y
T = T ^ Y
T = T & X;
0 1
0 2
13
14
twenty five
5 6
3 5
0 0
Sample Output 1
Four
6
0
<image>
For X = 5, Y = 6, proceed to vertices 0-> 2-> 5, and T = 5 & 6 = 4.
If X = 3, Y = 5, then go to vertices 0-> 1-> 4, and T = 3 ^ 5 = 6.
If X = 0, Y = 0, T does not change from 0 no matter where you go
Example
Input
6 3
T=T|X
T=T|Y
T=T|Y
T=T^Y
T=T&X
0 1
0 2
1 3
1 4
2 5
5 6
3 5
0 0
Output
4
6
0 | instruction | 0 | 80,770 | 13 | 161,540 |
"Correct Solution:
```
from collections import deque
from itertools import permutations
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
N, M = map(int, readline().split())
OP = [0]*N
ops = ["T=T&X\n", "T=T&Y\n", "T=T|X\n", "T=T|Y\n", "T=T^X\n", "T=T^Y\n"]
for i in range(N-1):
s = readline()
OP[i+1] = ops.index(s)
G = [[] for i in range(N)]
for i in range(N-1):
u, v = map(int, readline().split())
G[u].append(v)
G[v].append(u)
used = [0]*N
used[0] = 1
P = [-1]*N
V = []
D = [0]*N
que = deque([0])
for i in range(N):
v = que.popleft()
d = D[v]+1
for w in G[v]:
if used[w]:
continue
used[w] = 1
que.append(w)
P[w] = v
D[w] = d
V.append(w)
def check(x, y):
S = [0]*N
for v in V:
op = OP[v]
s = S[P[v]]
if op & 1:
if op & 2:
s |= y
elif op & 4:
s ^= y
else:
s &= y
else:
if op & 2:
s |= x
elif op & 4:
s ^= x
else:
s &= x
S[v] = s
T = [-1]*N
for v in reversed(V):
if T[v] == -1:
T[v] = S[v]
p = P[v]
if D[v] & 1:
T[p] = max(T[p], T[v]) if T[p] != -1 else T[v]
else:
T[p] = min(T[p], T[v]) if T[p] != -1 else T[v]
return T[0]
Q = [(1, 1), (1, 0), (0, 1)]
R = {}
for (x0, y0), (x1, y1), (x2, y2) in permutations(Q):
x = x0 + x1*2 + x2*4
y = y0 + y1*2 + y2*4
d = check(x, y)
d0 = d & 1; d1 = +((d & 2) > 0); d2 = +((d & 4) > 0)
R[(x0, x1, x2), (y0, y1, y2)] = (d0, d1, d2)
R[(x1, x2), (y1, y2)] = (d1, d2)
R[(x2,), (y2,)] = (d2,)
for i in range(M):
x, y = map(int, readline().split())
c = 0
E = {}
Q = []
x0 = x; y0 = y
while x0 or y0:
x1 = x0 & 1; y1 = y0 & 1
if x1 or y1:
E[x1, y1] = c
Q.append((x1, y1))
x0 >>= 1; y0 >>= 1
c += 1
if not E:
write("0\n")
continue
*S, = E.keys()
S.sort(key = E.__getitem__)
x1 = tuple(p for p, q in S)
y1 = tuple(q for p, q in S)
d1 = R[x1, y1]
for p, q, d in zip(x1, y1, d1):
E[p, q] = d
Q.reverse()
ans = 0
for p, q in Q:
if p or q:
ans = (ans << 1) | E[p, q]
else:
ans <<= 1
write("%d\n" % ans)
solve()
``` | output | 1 | 80,770 | 13 | 161,541 |
Provide a correct Python 3 solution for this coding contest problem.
Depth-first search (DFS) follows the strategy to search ”deeper” in the graph whenever possible. In DFS, edges are recursively explored out of the most recently discovered vertex $v$ that still has unexplored edges leaving it. When all of $v$'s edges have been explored, the search ”backtracks” to explore edges leaving the vertex from which $v$ was discovered.
This process continues until all the vertices that are reachable from the original source vertex have been discovered. If any undiscovered vertices remain, then one of them is selected as a new source and the search is repeated from that source.
DFS timestamps each vertex as follows:
* $d[v]$ records when $v$ is first discovered.
* $f[v]$ records when the search finishes examining $v$’s adjacency list.
Write a program which reads a directed graph $G = (V, E)$ and demonstrates DFS on the graph based on the following rules:
* $G$ is given in an adjacency-list. Vertices are identified by IDs $1, 2,... n$ respectively.
* IDs in the adjacency list are arranged in ascending order.
* The program should report the discover time and the finish time for each vertex.
* When there are several candidates to visit during DFS, the algorithm should select the vertex with the smallest ID.
* The timestamp starts with 1.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices of $G$ is given. In the next $n$ lines, adjacency lists of $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree. $v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex, print $id$, $d$ and $f$ separated by a space character in a line. $id$ is ID of the vertex, $d$ and $f$ is the discover time and the finish time respectively. Print in order of vertex IDs.
Examples
Input
4
1 1 2
2 1 4
3 0
4 1 3
Output
1 1 8
2 2 7
3 4 5
4 3 6
Input
6
1 2 2 3
2 2 3 4
3 1 5
4 1 6
5 1 6
6 0
Output
1 1 12
2 2 11
3 3 8
4 9 10
5 4 7
6 5 6 | instruction | 0 | 80,781 | 13 | 161,562 |
"Correct Solution:
```
from sys import stdin
readline=stdin.readline
#入力
n=int(readline())
m=n+1
u,k,v=[0]*m,[0]*m,[0]*m
for i in range(1,m):
u[i],k[i],*v[i]=map(int,readline().split())
d=[0]*m
f=[0]*m
flags=[False]*m
t=0
def dfs(now):
global t
t+=1
d[now]=t
flags[now]=True
for nex in v[now]:
if flags[nex]==False:
dfs(nex)
t+=1
f[now]=t
now=1
while True:
dfs(now)
for i in range(1,m):
if flags[i]==False:
now=i
break
else:
break
for i in range(1,m):
print(i,d[i],f[i])
``` | output | 1 | 80,781 | 13 | 161,563 |
Provide a correct Python 3 solution for this coding contest problem.
Depth-first search (DFS) follows the strategy to search ”deeper” in the graph whenever possible. In DFS, edges are recursively explored out of the most recently discovered vertex $v$ that still has unexplored edges leaving it. When all of $v$'s edges have been explored, the search ”backtracks” to explore edges leaving the vertex from which $v$ was discovered.
This process continues until all the vertices that are reachable from the original source vertex have been discovered. If any undiscovered vertices remain, then one of them is selected as a new source and the search is repeated from that source.
DFS timestamps each vertex as follows:
* $d[v]$ records when $v$ is first discovered.
* $f[v]$ records when the search finishes examining $v$’s adjacency list.
Write a program which reads a directed graph $G = (V, E)$ and demonstrates DFS on the graph based on the following rules:
* $G$ is given in an adjacency-list. Vertices are identified by IDs $1, 2,... n$ respectively.
* IDs in the adjacency list are arranged in ascending order.
* The program should report the discover time and the finish time for each vertex.
* When there are several candidates to visit during DFS, the algorithm should select the vertex with the smallest ID.
* The timestamp starts with 1.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices of $G$ is given. In the next $n$ lines, adjacency lists of $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree. $v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex, print $id$, $d$ and $f$ separated by a space character in a line. $id$ is ID of the vertex, $d$ and $f$ is the discover time and the finish time respectively. Print in order of vertex IDs.
Examples
Input
4
1 1 2
2 1 4
3 0
4 1 3
Output
1 1 8
2 2 7
3 4 5
4 3 6
Input
6
1 2 2 3
2 2 3 4
3 1 5
4 1 6
5 1 6
6 0
Output
1 1 12
2 2 11
3 3 8
4 9 10
5 4 7
6 5 6 | instruction | 0 | 80,782 | 13 | 161,564 |
"Correct Solution:
```
n=int(input())
D=[0]*(n+1)
F=[0]*(n+1)
v=[[] for i in range(n+1)]
flg=True
t=1
for i in range(n):
a=list(map(int,input().split()))
v[a[0]]=sorted(a[2:])
def dfs(p):
global t
if D[p]!=0: return
D[p]=t
t+=1
for i in v[p]:
if D[i]==0: dfs(i)
F[p]=t
t+=1
while flg:
flg=False
for i in range(1,n+1):
if D[i]==0:
flg=True
dfs(i)
for i in range(1,n+1):
print(f'{i} {D[i]} {F[i]}')
``` | output | 1 | 80,782 | 13 | 161,565 |
Provide a correct Python 3 solution for this coding contest problem.
Depth-first search (DFS) follows the strategy to search ”deeper” in the graph whenever possible. In DFS, edges are recursively explored out of the most recently discovered vertex $v$ that still has unexplored edges leaving it. When all of $v$'s edges have been explored, the search ”backtracks” to explore edges leaving the vertex from which $v$ was discovered.
This process continues until all the vertices that are reachable from the original source vertex have been discovered. If any undiscovered vertices remain, then one of them is selected as a new source and the search is repeated from that source.
DFS timestamps each vertex as follows:
* $d[v]$ records when $v$ is first discovered.
* $f[v]$ records when the search finishes examining $v$’s adjacency list.
Write a program which reads a directed graph $G = (V, E)$ and demonstrates DFS on the graph based on the following rules:
* $G$ is given in an adjacency-list. Vertices are identified by IDs $1, 2,... n$ respectively.
* IDs in the adjacency list are arranged in ascending order.
* The program should report the discover time and the finish time for each vertex.
* When there are several candidates to visit during DFS, the algorithm should select the vertex with the smallest ID.
* The timestamp starts with 1.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices of $G$ is given. In the next $n$ lines, adjacency lists of $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree. $v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex, print $id$, $d$ and $f$ separated by a space character in a line. $id$ is ID of the vertex, $d$ and $f$ is the discover time and the finish time respectively. Print in order of vertex IDs.
Examples
Input
4
1 1 2
2 1 4
3 0
4 1 3
Output
1 1 8
2 2 7
3 4 5
4 3 6
Input
6
1 2 2 3
2 2 3 4
3 1 5
4 1 6
5 1 6
6 0
Output
1 1 12
2 2 11
3 3 8
4 9 10
5 4 7
6 5 6 | instruction | 0 | 80,783 | 13 | 161,566 |
"Correct Solution:
```
n = int(input())
vert = [[0,0]+list(map(int,range(1,n+1)))]
parents = [0]
now = 0
time = 0
for i in range(n):
ukv = list(map(int,input().split()))
vert.append([0,0]+ukv[2:])
while(parents):
for i in range(2,len(vert[now])):
if vert[vert[now][i]][0] == 0:
parents.append(now)
now = vert[now][i]
time += 1
vert[now][0] = time
break
else:
if now != 0:
time += 1
vert[now][1] = time
now = parents.pop()
for i in range(1,n+1):
print(i,*vert[i][0:2])
``` | output | 1 | 80,783 | 13 | 161,567 |
Provide a correct Python 3 solution for this coding contest problem.
Depth-first search (DFS) follows the strategy to search ”deeper” in the graph whenever possible. In DFS, edges are recursively explored out of the most recently discovered vertex $v$ that still has unexplored edges leaving it. When all of $v$'s edges have been explored, the search ”backtracks” to explore edges leaving the vertex from which $v$ was discovered.
This process continues until all the vertices that are reachable from the original source vertex have been discovered. If any undiscovered vertices remain, then one of them is selected as a new source and the search is repeated from that source.
DFS timestamps each vertex as follows:
* $d[v]$ records when $v$ is first discovered.
* $f[v]$ records when the search finishes examining $v$’s adjacency list.
Write a program which reads a directed graph $G = (V, E)$ and demonstrates DFS on the graph based on the following rules:
* $G$ is given in an adjacency-list. Vertices are identified by IDs $1, 2,... n$ respectively.
* IDs in the adjacency list are arranged in ascending order.
* The program should report the discover time and the finish time for each vertex.
* When there are several candidates to visit during DFS, the algorithm should select the vertex with the smallest ID.
* The timestamp starts with 1.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices of $G$ is given. In the next $n$ lines, adjacency lists of $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree. $v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex, print $id$, $d$ and $f$ separated by a space character in a line. $id$ is ID of the vertex, $d$ and $f$ is the discover time and the finish time respectively. Print in order of vertex IDs.
Examples
Input
4
1 1 2
2 1 4
3 0
4 1 3
Output
1 1 8
2 2 7
3 4 5
4 3 6
Input
6
1 2 2 3
2 2 3 4
3 1 5
4 1 6
5 1 6
6 0
Output
1 1 12
2 2 11
3 3 8
4 9 10
5 4 7
6 5 6 | instruction | 0 | 80,784 | 13 | 161,568 |
"Correct Solution:
```
N = int(input())
adj_list = []
for _ in range(N):
line = list(input().split(" "))
adj_list.append([int(k) - 1 for k in line[2:]])
d = [-1 for _ in range(N)]
f = [-1 for _ in range(N)]
time = 1
visited = set()
def dfs(p):
global time
if p in visited:
return
d[p] = time
time += 1
visited.add(p)
for ad in adj_list[p]:
if ad not in visited:
dfs(ad)
f[p] = time
time += 1
for i in range(N):
dfs(i)
for i in range(N):
print(f"{i + 1} {d[i]} {f[i]}")
``` | output | 1 | 80,784 | 13 | 161,569 |
Provide a correct Python 3 solution for this coding contest problem.
Depth-first search (DFS) follows the strategy to search ”deeper” in the graph whenever possible. In DFS, edges are recursively explored out of the most recently discovered vertex $v$ that still has unexplored edges leaving it. When all of $v$'s edges have been explored, the search ”backtracks” to explore edges leaving the vertex from which $v$ was discovered.
This process continues until all the vertices that are reachable from the original source vertex have been discovered. If any undiscovered vertices remain, then one of them is selected as a new source and the search is repeated from that source.
DFS timestamps each vertex as follows:
* $d[v]$ records when $v$ is first discovered.
* $f[v]$ records when the search finishes examining $v$’s adjacency list.
Write a program which reads a directed graph $G = (V, E)$ and demonstrates DFS on the graph based on the following rules:
* $G$ is given in an adjacency-list. Vertices are identified by IDs $1, 2,... n$ respectively.
* IDs in the adjacency list are arranged in ascending order.
* The program should report the discover time and the finish time for each vertex.
* When there are several candidates to visit during DFS, the algorithm should select the vertex with the smallest ID.
* The timestamp starts with 1.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices of $G$ is given. In the next $n$ lines, adjacency lists of $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree. $v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex, print $id$, $d$ and $f$ separated by a space character in a line. $id$ is ID of the vertex, $d$ and $f$ is the discover time and the finish time respectively. Print in order of vertex IDs.
Examples
Input
4
1 1 2
2 1 4
3 0
4 1 3
Output
1 1 8
2 2 7
3 4 5
4 3 6
Input
6
1 2 2 3
2 2 3 4
3 1 5
4 1 6
5 1 6
6 0
Output
1 1 12
2 2 11
3 3 8
4 9 10
5 4 7
6 5 6 | instruction | 0 | 80,785 | 13 | 161,570 |
"Correct Solution:
```
import sys
time = 0
def dfs(u):
global time
flag_list[u] = 1
time += 1
d_list[u] = time
for v in range(n):
if m_list[u][v] == 1 and flag_list[v] == 0:
dfs(v)
flag_list[u] = 2
time += 1
f_list[u] = time
input = sys.stdin.readline
n = int(input())
m_list = [[0]*n for _ in range(n)]
for _ in range(n):
input_list = list(map(int, input().split()))
index = input_list[0] - 1
if input_list[1] > 0:
for a in input_list[2:]:
m_list[index][a-1] = 1
d_list = [0]*n
f_list = [0]*n
flag_list = [0]*n # 0: 未到達, 1: 処理中, 2: 完了
for i in range(n):
if flag_list[i] == 0:
dfs(i)
for i in range(n):
print(i+1, d_list[i], f_list[i])
``` | output | 1 | 80,785 | 13 | 161,571 |
Provide a correct Python 3 solution for this coding contest problem.
Depth-first search (DFS) follows the strategy to search ”deeper” in the graph whenever possible. In DFS, edges are recursively explored out of the most recently discovered vertex $v$ that still has unexplored edges leaving it. When all of $v$'s edges have been explored, the search ”backtracks” to explore edges leaving the vertex from which $v$ was discovered.
This process continues until all the vertices that are reachable from the original source vertex have been discovered. If any undiscovered vertices remain, then one of them is selected as a new source and the search is repeated from that source.
DFS timestamps each vertex as follows:
* $d[v]$ records when $v$ is first discovered.
* $f[v]$ records when the search finishes examining $v$’s adjacency list.
Write a program which reads a directed graph $G = (V, E)$ and demonstrates DFS on the graph based on the following rules:
* $G$ is given in an adjacency-list. Vertices are identified by IDs $1, 2,... n$ respectively.
* IDs in the adjacency list are arranged in ascending order.
* The program should report the discover time and the finish time for each vertex.
* When there are several candidates to visit during DFS, the algorithm should select the vertex with the smallest ID.
* The timestamp starts with 1.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices of $G$ is given. In the next $n$ lines, adjacency lists of $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree. $v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex, print $id$, $d$ and $f$ separated by a space character in a line. $id$ is ID of the vertex, $d$ and $f$ is the discover time and the finish time respectively. Print in order of vertex IDs.
Examples
Input
4
1 1 2
2 1 4
3 0
4 1 3
Output
1 1 8
2 2 7
3 4 5
4 3 6
Input
6
1 2 2 3
2 2 3 4
3 1 5
4 1 6
5 1 6
6 0
Output
1 1 12
2 2 11
3 3 8
4 9 10
5 4 7
6 5 6 | instruction | 0 | 80,786 | 13 | 161,572 |
"Correct Solution:
```
n=int(input())
E=[0]*n
for _ in range(n):
u,k,*V=map(int,input().split())
E[u-1]=sorted(V)[::-1]
todo=[1]
seen=[0]*n
d=[0]*n
f=[0]*n
t=0
while 0 in f:
if not todo:
todo.append(seen.index(0)+1)
if seen[todo[-1]-1]==0:
seen[todo[-1]-1]=1
t+=1
d[todo[-1]-1]=t
for v in E[todo[-1]-1]:
if d[v-1]==0:
todo.append(v)
elif f[todo[-1]-1]==0:
t+=1
f[todo.pop()-1]=t
else:
todo.pop()
for i in range(n):
print(i+1,d[i],f[i])
``` | output | 1 | 80,786 | 13 | 161,573 |
Provide a correct Python 3 solution for this coding contest problem.
Depth-first search (DFS) follows the strategy to search ”deeper” in the graph whenever possible. In DFS, edges are recursively explored out of the most recently discovered vertex $v$ that still has unexplored edges leaving it. When all of $v$'s edges have been explored, the search ”backtracks” to explore edges leaving the vertex from which $v$ was discovered.
This process continues until all the vertices that are reachable from the original source vertex have been discovered. If any undiscovered vertices remain, then one of them is selected as a new source and the search is repeated from that source.
DFS timestamps each vertex as follows:
* $d[v]$ records when $v$ is first discovered.
* $f[v]$ records when the search finishes examining $v$’s adjacency list.
Write a program which reads a directed graph $G = (V, E)$ and demonstrates DFS on the graph based on the following rules:
* $G$ is given in an adjacency-list. Vertices are identified by IDs $1, 2,... n$ respectively.
* IDs in the adjacency list are arranged in ascending order.
* The program should report the discover time and the finish time for each vertex.
* When there are several candidates to visit during DFS, the algorithm should select the vertex with the smallest ID.
* The timestamp starts with 1.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices of $G$ is given. In the next $n$ lines, adjacency lists of $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree. $v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex, print $id$, $d$ and $f$ separated by a space character in a line. $id$ is ID of the vertex, $d$ and $f$ is the discover time and the finish time respectively. Print in order of vertex IDs.
Examples
Input
4
1 1 2
2 1 4
3 0
4 1 3
Output
1 1 8
2 2 7
3 4 5
4 3 6
Input
6
1 2 2 3
2 2 3 4
3 1 5
4 1 6
5 1 6
6 0
Output
1 1 12
2 2 11
3 3 8
4 9 10
5 4 7
6 5 6 | instruction | 0 | 80,787 | 13 | 161,574 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(3000)
n = int(input())
X = []
for _ in range(n):
x = list(map(int, input().split()))
if x[1] != 0:
X.append(x[2:])
else:
X.append([])
df = [[0, 0] for _ in range(n)]
t = 0
def search(i = 0):
global t
if df[i][0] == 0:
t += 1
df[i][0] = t
for x in X[i]:
if df[x - 1][0] == 0:
search(x - 1)
if df[i][1] == 0:
t += 1
df[i][1] = t
for i in range(n):
search(i)
for i, x in enumerate(df):
print('{} {} {}'.format(i + 1, x[0], x[1]))
``` | output | 1 | 80,787 | 13 | 161,575 |
Provide a correct Python 3 solution for this coding contest problem.
Depth-first search (DFS) follows the strategy to search ”deeper” in the graph whenever possible. In DFS, edges are recursively explored out of the most recently discovered vertex $v$ that still has unexplored edges leaving it. When all of $v$'s edges have been explored, the search ”backtracks” to explore edges leaving the vertex from which $v$ was discovered.
This process continues until all the vertices that are reachable from the original source vertex have been discovered. If any undiscovered vertices remain, then one of them is selected as a new source and the search is repeated from that source.
DFS timestamps each vertex as follows:
* $d[v]$ records when $v$ is first discovered.
* $f[v]$ records when the search finishes examining $v$’s adjacency list.
Write a program which reads a directed graph $G = (V, E)$ and demonstrates DFS on the graph based on the following rules:
* $G$ is given in an adjacency-list. Vertices are identified by IDs $1, 2,... n$ respectively.
* IDs in the adjacency list are arranged in ascending order.
* The program should report the discover time and the finish time for each vertex.
* When there are several candidates to visit during DFS, the algorithm should select the vertex with the smallest ID.
* The timestamp starts with 1.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices of $G$ is given. In the next $n$ lines, adjacency lists of $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree. $v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex, print $id$, $d$ and $f$ separated by a space character in a line. $id$ is ID of the vertex, $d$ and $f$ is the discover time and the finish time respectively. Print in order of vertex IDs.
Examples
Input
4
1 1 2
2 1 4
3 0
4 1 3
Output
1 1 8
2 2 7
3 4 5
4 3 6
Input
6
1 2 2 3
2 2 3 4
3 1 5
4 1 6
5 1 6
6 0
Output
1 1 12
2 2 11
3 3 8
4 9 10
5 4 7
6 5 6 | instruction | 0 | 80,788 | 13 | 161,576 |
"Correct Solution:
```
n = int(input())
al = [list(map(lambda s: int(s) - 1, input().split()))[2:] for _ in range(n)]
begin = [-1] * n
end = [-1] * n
not_visited = list(range(n))
t = 1
def dfs(u):
global begin, end, t, not_visited
begin[u] = t
t += 1
not_visited.remove(u)
for v in al[u]:
if begin[v] == -1:
dfs(v)
end[u] = t
t += 1
while len(not_visited) > 0:
dfs(not_visited[0])
for i in range(n):
print('{} {} {}'.format(i + 1, begin[i], end[i]))
``` | output | 1 | 80,788 | 13 | 161,577 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Depth-first search (DFS) follows the strategy to search ”deeper” in the graph whenever possible. In DFS, edges are recursively explored out of the most recently discovered vertex $v$ that still has unexplored edges leaving it. When all of $v$'s edges have been explored, the search ”backtracks” to explore edges leaving the vertex from which $v$ was discovered.
This process continues until all the vertices that are reachable from the original source vertex have been discovered. If any undiscovered vertices remain, then one of them is selected as a new source and the search is repeated from that source.
DFS timestamps each vertex as follows:
* $d[v]$ records when $v$ is first discovered.
* $f[v]$ records when the search finishes examining $v$’s adjacency list.
Write a program which reads a directed graph $G = (V, E)$ and demonstrates DFS on the graph based on the following rules:
* $G$ is given in an adjacency-list. Vertices are identified by IDs $1, 2,... n$ respectively.
* IDs in the adjacency list are arranged in ascending order.
* The program should report the discover time and the finish time for each vertex.
* When there are several candidates to visit during DFS, the algorithm should select the vertex with the smallest ID.
* The timestamp starts with 1.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices of $G$ is given. In the next $n$ lines, adjacency lists of $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree. $v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex, print $id$, $d$ and $f$ separated by a space character in a line. $id$ is ID of the vertex, $d$ and $f$ is the discover time and the finish time respectively. Print in order of vertex IDs.
Examples
Input
4
1 1 2
2 1 4
3 0
4 1 3
Output
1 1 8
2 2 7
3 4 5
4 3 6
Input
6
1 2 2 3
2 2 3 4
3 1 5
4 1 6
5 1 6
6 0
Output
1 1 12
2 2 11
3 3 8
4 9 10
5 4 7
6 5 6
Submitted Solution:
```
n = int(input())
a = [[0]*n for i in range(n)]
for i in range(n):
v = list(map(int, input().split()))
u = v[0]
k = v[1]
for j in range(k):
a[u - 1][v[2 + j] - 1] = 1
d = [0] * n
f = [0] * n
isDiscovered = [False] * n
time_stamp = 0
def dfs(x):
global time_stamp
isDiscovered [x] = True
time_stamp = time_stamp + 1
d[x] = time_stamp
for i in range(n):
if a[x][i] == 1 and isDiscovered[i] == False:
dfs(i)
time_stamp = time_stamp + 1
f[x] = time_stamp
for i in range(n):
if isDiscovered[i] == False:
dfs(i)
for i in range(n):
print(i+1, d[i], f[i])
``` | instruction | 0 | 80,789 | 13 | 161,578 |
Yes | output | 1 | 80,789 | 13 | 161,579 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Depth-first search (DFS) follows the strategy to search ”deeper” in the graph whenever possible. In DFS, edges are recursively explored out of the most recently discovered vertex $v$ that still has unexplored edges leaving it. When all of $v$'s edges have been explored, the search ”backtracks” to explore edges leaving the vertex from which $v$ was discovered.
This process continues until all the vertices that are reachable from the original source vertex have been discovered. If any undiscovered vertices remain, then one of them is selected as a new source and the search is repeated from that source.
DFS timestamps each vertex as follows:
* $d[v]$ records when $v$ is first discovered.
* $f[v]$ records when the search finishes examining $v$’s adjacency list.
Write a program which reads a directed graph $G = (V, E)$ and demonstrates DFS on the graph based on the following rules:
* $G$ is given in an adjacency-list. Vertices are identified by IDs $1, 2,... n$ respectively.
* IDs in the adjacency list are arranged in ascending order.
* The program should report the discover time and the finish time for each vertex.
* When there are several candidates to visit during DFS, the algorithm should select the vertex with the smallest ID.
* The timestamp starts with 1.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices of $G$ is given. In the next $n$ lines, adjacency lists of $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree. $v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex, print $id$, $d$ and $f$ separated by a space character in a line. $id$ is ID of the vertex, $d$ and $f$ is the discover time and the finish time respectively. Print in order of vertex IDs.
Examples
Input
4
1 1 2
2 1 4
3 0
4 1 3
Output
1 1 8
2 2 7
3 4 5
4 3 6
Input
6
1 2 2 3
2 2 3 4
3 1 5
4 1 6
5 1 6
6 0
Output
1 1 12
2 2 11
3 3 8
4 9 10
5 4 7
6 5 6
Submitted Solution:
```
def depth_search(i, adj, d, f, t):
if d[i - 1]:
return t
d[i - 1] = t
t += 1
for v in adj[i - 1]:
t = depth_search(v, adj, d, f, t)
f[i - 1] = t
t += 1
return t
n = int(input())
adj = [list(map(int, input().split()))[2:] for _ in range(n)]
d = [0] * n
f = [0] * n
t = 1
for i in range(n):
if d[i] == 0:
t = depth_search(i + 1, adj, d, f, t)
for i, df in enumerate(zip(d, f)):
print(i + 1, *df)
``` | instruction | 0 | 80,790 | 13 | 161,580 |
Yes | output | 1 | 80,790 | 13 | 161,581 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Depth-first search (DFS) follows the strategy to search ”deeper” in the graph whenever possible. In DFS, edges are recursively explored out of the most recently discovered vertex $v$ that still has unexplored edges leaving it. When all of $v$'s edges have been explored, the search ”backtracks” to explore edges leaving the vertex from which $v$ was discovered.
This process continues until all the vertices that are reachable from the original source vertex have been discovered. If any undiscovered vertices remain, then one of them is selected as a new source and the search is repeated from that source.
DFS timestamps each vertex as follows:
* $d[v]$ records when $v$ is first discovered.
* $f[v]$ records when the search finishes examining $v$’s adjacency list.
Write a program which reads a directed graph $G = (V, E)$ and demonstrates DFS on the graph based on the following rules:
* $G$ is given in an adjacency-list. Vertices are identified by IDs $1, 2,... n$ respectively.
* IDs in the adjacency list are arranged in ascending order.
* The program should report the discover time and the finish time for each vertex.
* When there are several candidates to visit during DFS, the algorithm should select the vertex with the smallest ID.
* The timestamp starts with 1.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices of $G$ is given. In the next $n$ lines, adjacency lists of $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree. $v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex, print $id$, $d$ and $f$ separated by a space character in a line. $id$ is ID of the vertex, $d$ and $f$ is the discover time and the finish time respectively. Print in order of vertex IDs.
Examples
Input
4
1 1 2
2 1 4
3 0
4 1 3
Output
1 1 8
2 2 7
3 4 5
4 3 6
Input
6
1 2 2 3
2 2 3 4
3 1 5
4 1 6
5 1 6
6 0
Output
1 1 12
2 2 11
3 3 8
4 9 10
5 4 7
6 5 6
Submitted Solution:
```
def depthFirstSearch(i, Adj, d, f, t):
if d[i - 1]:
return t
d[i - 1] = t
t += 1
for v in Adj[i - 1]:
t = depthFirstSearch(v, Adj, d, f, t)
f[i - 1] = t
t += 1
return t
n = int(input())
Adj = [list(map(int, input().split()))[2:] for _ in range(n)]
d = [0] * n
f = [0] * n
t = 1
for i in range(n):
if d[i] == 0:
t = depthFirstSearch(i + 1, Adj, d, f, t)
for i, df in enumerate(zip(d, f)):
print(i + 1, *df)
``` | instruction | 0 | 80,791 | 13 | 161,582 |
Yes | output | 1 | 80,791 | 13 | 161,583 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Depth-first search (DFS) follows the strategy to search ”deeper” in the graph whenever possible. In DFS, edges are recursively explored out of the most recently discovered vertex $v$ that still has unexplored edges leaving it. When all of $v$'s edges have been explored, the search ”backtracks” to explore edges leaving the vertex from which $v$ was discovered.
This process continues until all the vertices that are reachable from the original source vertex have been discovered. If any undiscovered vertices remain, then one of them is selected as a new source and the search is repeated from that source.
DFS timestamps each vertex as follows:
* $d[v]$ records when $v$ is first discovered.
* $f[v]$ records when the search finishes examining $v$’s adjacency list.
Write a program which reads a directed graph $G = (V, E)$ and demonstrates DFS on the graph based on the following rules:
* $G$ is given in an adjacency-list. Vertices are identified by IDs $1, 2,... n$ respectively.
* IDs in the adjacency list are arranged in ascending order.
* The program should report the discover time and the finish time for each vertex.
* When there are several candidates to visit during DFS, the algorithm should select the vertex with the smallest ID.
* The timestamp starts with 1.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices of $G$ is given. In the next $n$ lines, adjacency lists of $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree. $v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex, print $id$, $d$ and $f$ separated by a space character in a line. $id$ is ID of the vertex, $d$ and $f$ is the discover time and the finish time respectively. Print in order of vertex IDs.
Examples
Input
4
1 1 2
2 1 4
3 0
4 1 3
Output
1 1 8
2 2 7
3 4 5
4 3 6
Input
6
1 2 2 3
2 2 3 4
3 1 5
4 1 6
5 1 6
6 0
Output
1 1 12
2 2 11
3 3 8
4 9 10
5 4 7
6 5 6
Submitted Solution:
```
def main():
inf = 1000000007
n = int(input())
e = [[] for _ in range(n)]
d = [inf]*n
f = [inf]*n
step = 1
def dfs(v):
nonlocal step
d[v] = step
step+=1
for u in e[v]:
if d[u] == inf:dfs(u)
f[v] = step
step +=1
e = [[] for _ in range(n)]
for i in range(n):
m = list(map(int,input().split()))
for j in range(2,len(m)):
e[m[0]-1].append(m[j]-1)
for i in range(n):
if d[i]==inf:dfs(i)
for i in range(n):
print (i+1,d[i],f[i])
if __name__ == '__main__':
main()
``` | instruction | 0 | 80,792 | 13 | 161,584 |
Yes | output | 1 | 80,792 | 13 | 161,585 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Depth-first search (DFS) follows the strategy to search ”deeper” in the graph whenever possible. In DFS, edges are recursively explored out of the most recently discovered vertex $v$ that still has unexplored edges leaving it. When all of $v$'s edges have been explored, the search ”backtracks” to explore edges leaving the vertex from which $v$ was discovered.
This process continues until all the vertices that are reachable from the original source vertex have been discovered. If any undiscovered vertices remain, then one of them is selected as a new source and the search is repeated from that source.
DFS timestamps each vertex as follows:
* $d[v]$ records when $v$ is first discovered.
* $f[v]$ records when the search finishes examining $v$’s adjacency list.
Write a program which reads a directed graph $G = (V, E)$ and demonstrates DFS on the graph based on the following rules:
* $G$ is given in an adjacency-list. Vertices are identified by IDs $1, 2,... n$ respectively.
* IDs in the adjacency list are arranged in ascending order.
* The program should report the discover time and the finish time for each vertex.
* When there are several candidates to visit during DFS, the algorithm should select the vertex with the smallest ID.
* The timestamp starts with 1.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices of $G$ is given. In the next $n$ lines, adjacency lists of $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree. $v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex, print $id$, $d$ and $f$ separated by a space character in a line. $id$ is ID of the vertex, $d$ and $f$ is the discover time and the finish time respectively. Print in order of vertex IDs.
Examples
Input
4
1 1 2
2 1 4
3 0
4 1 3
Output
1 1 8
2 2 7
3 4 5
4 3 6
Input
6
1 2 2 3
2 2 3 4
3 1 5
4 1 6
5 1 6
6 0
Output
1 1 12
2 2 11
3 3 8
4 9 10
5 4 7
6 5 6
Submitted Solution:
```
#coding: utf-8
n = int(input())
color = ["white" for i in range(n)]
d = [[] for i in range(n)]
global t
t = 0
M = [[False for i in range(n)] for j in range(n)]
for i in range(n):
data = list(map(int,input().split()))
u = data[0]
k = data[1]
if i == 0:
start = u
for v in data[2:2+k]:
M[u-1][v-1] = True
def search(u,t):
t += 1
color[u-1] = "gray"
d[u-1].append(t)
for v in range(n):
if M[u-1][v-1] and color[v-1] == "white":
t = search(v,t)
color[u-1] = "black"
t += 1
d[u-1].append(t)
return t
t = search(start, t)
for i in range(n):
if color[i-1] == "white":
t += 1
t = search(i, t)
for i in range(n):
print(i+1, d[i][0], d[i][1])
``` | instruction | 0 | 80,793 | 13 | 161,586 |
No | output | 1 | 80,793 | 13 | 161,587 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Depth-first search (DFS) follows the strategy to search ”deeper” in the graph whenever possible. In DFS, edges are recursively explored out of the most recently discovered vertex $v$ that still has unexplored edges leaving it. When all of $v$'s edges have been explored, the search ”backtracks” to explore edges leaving the vertex from which $v$ was discovered.
This process continues until all the vertices that are reachable from the original source vertex have been discovered. If any undiscovered vertices remain, then one of them is selected as a new source and the search is repeated from that source.
DFS timestamps each vertex as follows:
* $d[v]$ records when $v$ is first discovered.
* $f[v]$ records when the search finishes examining $v$’s adjacency list.
Write a program which reads a directed graph $G = (V, E)$ and demonstrates DFS on the graph based on the following rules:
* $G$ is given in an adjacency-list. Vertices are identified by IDs $1, 2,... n$ respectively.
* IDs in the adjacency list are arranged in ascending order.
* The program should report the discover time and the finish time for each vertex.
* When there are several candidates to visit during DFS, the algorithm should select the vertex with the smallest ID.
* The timestamp starts with 1.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices of $G$ is given. In the next $n$ lines, adjacency lists of $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree. $v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex, print $id$, $d$ and $f$ separated by a space character in a line. $id$ is ID of the vertex, $d$ and $f$ is the discover time and the finish time respectively. Print in order of vertex IDs.
Examples
Input
4
1 1 2
2 1 4
3 0
4 1 3
Output
1 1 8
2 2 7
3 4 5
4 3 6
Input
6
1 2 2 3
2 2 3 4
3 1 5
4 1 6
5 1 6
6 0
Output
1 1 12
2 2 11
3 3 8
4 9 10
5 4 7
6 5 6
Submitted Solution:
```
n=int(input())
next=[[] for i in range(n)]
for i in range(n):
l=list(map(int,input().split()))
u=l[0]
k=l[1]
for j in range(2,k+2):
next[u-1].append(l[j]-1)
stk=[]
stk.append(0)
print(next)
time=1
d=[0 for i in range(n)]
f=[0 for i in range(n)]
while(len(stk)!=0):
if len(next[stk[-1]])==0:
if d[stk[-1]]==0:
d[stk[-1]]=time
#print(stk[-1])
time+=1
f[stk[-1]]=time
#print(stk[-1])
time+=1
stk.pop()
else:
v=min(next[stk[-1]])
if d[v]!=0:
next[stk[-1]].remove(v)
else:
if d[stk[-1]]==0:
d[stk[-1]]=time
time+=1
#print(stk[-1])
next[stk[-1]].remove(v)
stk.append(v)
for i in range(n):
out=[]
out.append(i+1)
out.append(d[i])
out.append(f[i])
print(*out)
``` | instruction | 0 | 80,794 | 13 | 161,588 |
No | output | 1 | 80,794 | 13 | 161,589 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Depth-first search (DFS) follows the strategy to search ”deeper” in the graph whenever possible. In DFS, edges are recursively explored out of the most recently discovered vertex $v$ that still has unexplored edges leaving it. When all of $v$'s edges have been explored, the search ”backtracks” to explore edges leaving the vertex from which $v$ was discovered.
This process continues until all the vertices that are reachable from the original source vertex have been discovered. If any undiscovered vertices remain, then one of them is selected as a new source and the search is repeated from that source.
DFS timestamps each vertex as follows:
* $d[v]$ records when $v$ is first discovered.
* $f[v]$ records when the search finishes examining $v$’s adjacency list.
Write a program which reads a directed graph $G = (V, E)$ and demonstrates DFS on the graph based on the following rules:
* $G$ is given in an adjacency-list. Vertices are identified by IDs $1, 2,... n$ respectively.
* IDs in the adjacency list are arranged in ascending order.
* The program should report the discover time and the finish time for each vertex.
* When there are several candidates to visit during DFS, the algorithm should select the vertex with the smallest ID.
* The timestamp starts with 1.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices of $G$ is given. In the next $n$ lines, adjacency lists of $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree. $v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex, print $id$, $d$ and $f$ separated by a space character in a line. $id$ is ID of the vertex, $d$ and $f$ is the discover time and the finish time respectively. Print in order of vertex IDs.
Examples
Input
4
1 1 2
2 1 4
3 0
4 1 3
Output
1 1 8
2 2 7
3 4 5
4 3 6
Input
6
1 2 2 3
2 2 3 4
3 1 5
4 1 6
5 1 6
6 0
Output
1 1 12
2 2 11
3 3 8
4 9 10
5 4 7
6 5 6
Submitted Solution:
```
#16D8101014F KurumeRyunosuke 2018/6/20
n=int(input())
ls=[[0 for i in range(n)]for j in range(n)]
for i in range(n):
tmp=input().split()
for j in range(int(tmp[1])):
ls[i][int(tmp[j+2])-1]=1
"""
for i in range(n):
for j in range(n):
if(j!=n-1):
print(int(ls[i][j]), end=' ')
else:
print(int(ls[i][j]))
"""
stuck=[0]
count=1
d=[0 for i in range(n)]
f=[0 for i in range(n)]
d[0]=count
while True:
count+=1
p=0
for i in range(n):
if ls[stuck[len(stuck)-1]][i] is not 0:
ls[stuck[len(stuck)-1]][i]=0
p=1
#print(stuck)
stuck.append(i)
d[stuck[len(stuck)-1]]=count
break
if p is 1:
for i in range(n):
ls[i][stuck[len(stuck)-1]]=0
if p is 0:
#print("//")
a=stuck.pop()
f[a]=count
for i in range(n):
ls[a][i]=0
if len(stuck) is 0:
#print("break")
break
for i in range(n):
print(i+1,d[i],f[i])
``` | instruction | 0 | 80,795 | 13 | 161,590 |
No | output | 1 | 80,795 | 13 | 161,591 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.