def perm_num_cycles(p, n=None):
    """
    Return the number of cycles of the permutation ``p``.

    EXAMPLES::

        sage: from surface_dynamics.misc.permutation import perm_num_cycles
        sage: perm_num_cycles([1,2,3,0])
        1
        sage: perm_num_cycles([0,2,3,1])
        2
        sage: perm_num_cycles([3,2,1,0])
        2
        sage: perm_num_cycles([3,1,2,0])
        3
        sage: perm_num_cycles([0,1,2,3])
        4
    """
    if n is None:
        n = len(p)
    seen = [False] * n
    ans = 0
    for i in range(n):
        if seen[i] or p[i] == -1:
            continue
        ans += 1
        j = i
        while not seen[j]:
            seen[j] = True
            j = p[j]
    return ans
