Untitled
unknown
plain_text
2 years ago
568 B
8
Indexable
int longestCycle(vector<int>& edges) {
vector<pair<int, int>> took(edges.size()); // did we take the outgoing edge from i?
int ans = -1;
for (int node = 0; node < edges.size(); ++node) {
int len = 1, cur = node;
while (cur != -1 && took[cur].second == 0) {
took[cur] = make_pair(node, len++);
cur = edges[cur];
}
if (cur != -1 && took[cur].first == node) {
ans = max(ans, len - took[cur].second);
}
}
return ans;
} Editor is loading...
Leave a Comment