3
int longestCycle(vector<int> &edges) {4
int ans = -1; // Initialize the answer to -15
int time = 1; // Initialize the current time step to 16
vector<int> timeVisited(edges.size()); // Initialize a vector to store the time at which each7
// node was first visited9
// Iterate through each node in the graph10
for (int i = 0; i < edges.size(); ++i) {11
if (timeVisited[i]) // If the node has already been visited, skip it13
const int startTime = time; // Record the start time of the current traversal14
int u = i; // Initialize the current node to the ith node15
// Traverse the graph until the end of the path is reached or a visited16
// node is encountered17
while (u != -1 && !timeVisited[u]) {18
timeVisited[u] = time++; // Record the current time step and increment time19
u = edges[u]; // Move to the next node in the path21
// If a cycle is found that includes the current node, update the answer22
if (u != -1 && timeVisited[u] >= startTime) ans = max(ans, time - timeVisited[u]);25
return ans; // Return the length of the longest cycle found