<p>You are given a <strong>directed</strong> graph of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code>, where each node has <strong>at most one</strong> outgoing edge.</p>

<p>The graph is represented with a given <strong>0-indexed</strong> array <code>edges</code> of size <code>n</code>, indicating that there is a directed edge from node <code>i</code> to node <code>edges[i]</code>. If there is no outgoing edge from node <code>i</code>, then <code>edges[i] == -1</code>.</p>

<p>Return <em>the length of the <strong>longest</strong> cycle in the graph</em>. If no cycle exists, return <code>-1</code>.</p>

<p>A cycle is a path that starts and ends at the <strong>same</strong> node.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2022/06/08/graph4drawio-5.png" style="width: 335px; height: 191px;" />
<pre>
<strong>Input:</strong> edges = [3,3,4,2,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The longest cycle in the graph is the cycle: 2 -&gt; 4 -&gt; 3 -&gt; 2.
The length of this cycle is 3, so 3 is returned.
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2022/06/07/graph4drawio-1.png" style="width: 171px; height: 161px;" />
<pre>
<strong>Input:</strong> edges = [2,-1,3,1]
<strong>Output:</strong> -1
<strong>Explanation:</strong> There are no cycles in this graph.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>n == edges.length</code></li>
	<li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li>
	<li><code>-1 &lt;= edges[i] &lt; n</code></li>
	<li><code>edges[i] != i</code></li>
</ul>

from typing import List
from collections import defaultdict
from collections import deque

class Solution:
    def longestCycle(self, edges: List[int]) -> int:

        class disjoint_sets:
            '''
            為了加速, 使用 list of int 來實作 union-find 用的 disjoint sets 
            另外, 紀錄目前所有的 roots, 可以即時算出 size, 以及找出所有的 roots
            '''
            def __init__(self, n):
                self.parent = list(range(n))
                self.tree_sizes = {i:1 for i in range(n)}
                
            def find(self, p):
                # 自己就是 root
                if self.parent[p] == p:
                    return p
                # update parents to root
                self.parent[p] = self.find(self.parent[p])
                return self.parent[p]

            # 將兩個 nodes 所在的兩個集合合併，並且傳回是否真的發生合併，False 表示原本就已經是同一個集合
            def union(self, a, b):
                root1, root2 = self.find(a), self.find(b)
                if root1 == root2:
                    return False
                else:
                    self.parent[root1] = root2
                    self.tree_sizes[root2] += self.tree_sizes[root1]
                    self.tree_sizes.pop(root1)
                    return True
            
            def __len__(self):
                return len(self.tree_sizes.keys())



        n = len(edges)
        parents = edges

        # 產生反向的 edges，可以視為 children
        children = defaultdict(list)
        for c, p in enumerate(parents):
            # 紀錄 p 有哪些小孩 c
            children[p].append(c)

        # print(children)

        # 使用 BFS，將所有以 -1 為 root 的 nodes 的 edge 設定為 -1
        # 表示為不可能產生 cycle 的 nodes
        queue = deque(children[-1])
        # print(f'queue={queue}')
        while queue:
            a = queue.popleft()
            parents[a] = -1
            queue.extend(children[a])
        # print(parents)

        # 接下來，只有那些 edge 不是 -1 的，才有可能產生 cycle
        # 但是考慮到會有多個 cycles，要避免重複計算，所以用 union-find (disjoint sets)
        ds = disjoint_sets(n)
        for c, p in enumerate(parents):
            if p != -1:
                ds.union(p, c)

        # 只有每個 group 的 root 要處理
        roots = sorted(root for root in ds.tree_sizes if ds.tree_sizes[root] > 1)

        cycle_lengths = [-1]  # 每次找到一個 cycle，就紀錄這個 cycle 的長度，如果都沒有則回傳 -1
        for i in roots:
            # 使用 Pollard's rho 演算法 的 快慢指針
            p1, p2 = i, edges[i]

            # 找到第一次交會點
            while p1 != p2:
                # print(f'p1={p1}, p2={p2}')
                p1 = edges[p1]
                p2 = edges[edges[p2]]
            # print(f'p1={p1}, p2={p2}')

            # 計算 cycle length
            cycle_len = 1
            p1 = edges[p1]
            p2 = edges[edges[p2]]
            while p1 != p2:
                cycle_len += 1
                p1 = edges[p1]
                p2 = edges[edges[p2]]
            
            # 紀錄 cycle length
            cycle_lengths.append(cycle_len)
            # print(f'i={i}, cycle_len={cycle_len}')

        return max(cycle_lengths)

1412