leetcodeSolution to some Leetcode problems written in C++ |
git clone git://git.dimitrijedobrota.com/leetcode.git |
Log | Files | Refs | README | LICENSE |
2360.cpp (832B)
0 class Solution { 1 public: 2 int longestCycle(vector<int> &edges) { 3 int n = edges.size(), res = -1; 4 vector<int> count(n, 0); 5 for (int edge : edges) 6 if (edge != -1) count[edge]++; 7 8 queue<int> q; 9 for (int i = 0; i < n; i++) 10 if (!count[i]) q.push(i); 11 12 while (!q.empty()) { 13 int root = q.front(); 14 q.pop(); 15 if (edges[root] == -1) continue; 16 if (--count[edges[root]] == 0) q.push(edges[root]); 17 } 18 19 for (int i = 0; i < n; i++) { 20 if (!count[i]) continue; 21 int k = i, num = 1; 22 while (edges[k] != i) { 23 count[k] = 0; 24 k = edges[k]; 25 num++; 26 } 27 res = max(res, num); 28 } 29 30 return res; 31 } 32 };