-
Notifications
You must be signed in to change notification settings - Fork 160
/
Copy pathDetect the longest cycle in an array.cpp
77 lines (48 loc) · 1.41 KB
/
Detect the longest cycle in an array.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
Given an array of integers where each element points to the index of the next element
how would you detect the longest cycle in this array.
Note: suppose the element of array is in range[0, n-1], where n is the length of array, then there
must be at least one cycle. If one element points itself, this particular cycle length is 1.
*/
/*
solution: DFS
O(n) time, O(n) space
*/
#include<iostream>
#include<vector>
#include<cassert>
using namespace std;
void detectLongestCycleInner(int start, int idx, int arr[], vector<bool>& visited, int &len) {
visited[idx] = true;
len++;
if (!visited[arr[idx]]) {
detectLongestCycleInner(start, arr[idx], arr, visited, len);
} else {
assert(start != idx); //a cycle
}
}
/*
Input: array arr[] and len as the length of arr[].
Output: the length of longest cycle.
*/
int DetectLongestCycle(int arr[], int len) {
int maxlen = 0;
int curlen = 0;
vector<bool> visited(n, false);
for (int i = 0; i <len; ++i) {
if (!visited[i]) {
detectLongestCycleInner(i, i, arr, visited, len);
if (curlen > maxlen) {
maxlen = curlen;
}
}
}
return maxlen;
}
}
int main() {
int a[] = {3, 2, 1, 4, 0};
int len = sizeof(arr)/sizeof(arr[0]);
cout<<DetectLongestCycle(a, len)<<endl;
return 0;
}