-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path10451.py
85 lines (62 loc) · 1.75 KB
/
10451.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import sys
sys.setrecursionlimit(10**6)
def get_cycle(n, arr):
edges = []
for i in range(1, n + 1):
info = [i, arr[i]]
edges.append(info)
# make adjacency list
r = [[] for i in range(n + 1)]
for u, v in edges:
r[u].append(v)
color = ["white" for i in range(n + 1)]
dist = [None for i in range(n + 1)]
def dfs(u, value):
for v in r[u]:
if color[v] == "white":
color[v] = "gray"
dist[v] = value
dfs(v, value)
color[u] = "black"
for i in range(1, n + 1):
dfs(i, i)
print(len(set(dist))-1)
if __name__ == "__main__":
test_case = int(input())
for _ in range(test_case):
n = int(input()) # number of vertex
arr = [int(x) for x in input().split()]
arr.insert(0, 0)
get_cycle(n, arr)
||||||| merged common ancestors
=======
import sys
sys.setrecursionlimit(10**6)
def get_cycle(n, arr):
edges = []
for i in range(1, n + 1):
info = [i, arr[i]]
edges.append(info)
# make adjacency list
r = [[] for i in range(n + 1)]
for u, v in edges:
r[u].append(v)
color = ["white" for i in range(n + 1)]
dist = [None for i in range(n + 1)]
def dfs(u, value):
for v in r[u]:
if color[v] == "white":
color[v] = "gray"
dist[v] = value
dfs(v, value)
color[u] = "black"
for i in range(1, n + 1):
dfs(i, i)
print(len(set(dist))-1)
if __name__ == "__main__":
test_case = int(input())
for _ in range(test_case):
n = int(input()) # number of vertex
arr = [int(x) for x in input().split()]
arr.insert(0, 0)
get_cycle(n, arr)