-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlanets Cycles.cpp
More file actions
executable file
·64 lines (60 loc) · 984 Bytes
/
Copy pathPlanets Cycles.cpp
File metadata and controls
executable file
·64 lines (60 loc) · 984 Bytes
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
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
vector<int> v[200009];
int odw[200009];
int res[200009];
int dfs(int s, int& cycle, int step) {
odw[s] = step;
int back = s;
for (int i : v[s]) {
if (res[i]) {
res[s] = res[i] + 1;
cycle = -1;
return s;
}
if (odw[i]) {
cycle = i;
if (v[s][0] == s) cycle = -1;
res[s] = step - odw[i] + 1;
return s;
}
if (odw[i] == 0) {
back = dfs(i, cycle, step + 1);
}
}
if (cycle == s) {
res[s] = res[back];
cycle = -1;
return s;
}
if (cycle == -1) {
res[s] = res[back] + 1;
} else {
res[s] = res[back];
}
return s;
}
void dfs_run(int n) {
for (int i = 1; i <= n; i++) {
if (odw[i] == 0) {
int cycle = 0;
dfs(i, cycle, 1);
}
}
}
int main() {
ios_base::sync_with_stdio(false);
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
int a;
cin >> a;
v[i].push_back(a);
}
dfs_run(n);
for (int i = 1; i <= n; i++) {
cout << res[i] << " ";
}
return 0;
}