-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathP12442.cpp
executable file
·61 lines (60 loc) · 1.17 KB
/
P12442.cpp
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
#define LIM 50001
bool visited[LIM], marked[LIM];
int nxt[LIM], ret[LIM];
int main() {
int x, y;
FORCAS {
GI(N);
FORI(N) {
cin >> x >> y; --x; --y;
nxt[x] = y;
visited[x] = marked[x] = false;
}
int best = 0;
// GO:
FORI(N) {
if(visited[i])
continue; // already visited.
x = i;
int steps = 0;
while(!visited[x] && !marked[x]) {
ret[x] = steps++;
marked[x] = true;
x = nxt[x];
}
if(!visited[x]) { // marked[x] == true
// New loop found:
int loopSize = steps - ret[x];
steps = ret[x];
//cerr << "Loop of size " << loopSize << " found." << endl;
// Mark all in loop:
ret[x] = loopSize;
marked[x] = false;
visited[x] = true;
y = nxt[x];
while(y != x) {
ret[y] = loopSize;
marked[y] = false;
visited[y] = true;
y = nxt[y];
}
}
// Feed into already visited:
y = i;
while(y != x) {
ret[y] = steps + ret[x];
marked[y] = false;
visited[y] = true;
y = nxt[y];
--steps;
}
if(ret[i] > ret[best])
best = i;
}
/*
FORI(N)
cerr << " ret[" << i << "]=" << ret[i] << endl;*/
cout << "Case " << cas+1 << ": " << best+1 << endl;
}
return 0;
}