JuspayOA #1
Converging Maze: Largest Sum Cycle
Estimated MediumJudge-ready
Topics (AI-labelled)Union-Find
Each cell numbered 0..N−1 has at most one one-way exit edge[i]; edge[i]=−1 means it has no exit. Output the maximum sum of node numbers over all directed cycles; output −1 if there is no cycle.
Input
The first line contains N (1..200000), and the second line contains N integers, each either −1 or in [0,N−1].
Output
Output the maximum sum of node numbers in a cycle, or −1.
Example 1
Input:
23
4 4 1 4 13 8 8 8 0 8 14 9 15 11 -1 10 15 22 22 22 22 22 21
Output:
45
Example 2
Input:
1
-1
Output:
-1
Example 3
Input:
4
1 0 3 2
Output:
5
Editorial
Loading solution…