import torch


def inverse_permutation(perm):
    """
    Inverse a permutation.

    .. warning::
        This function does not check the validness of the input. That is, if the input is not a permutation, this
        function may generate arbitrary output.

    Args:
        perm (LongTensor): shape `(N, )` representing a permutation of 0 ~ N - 1.

    Returns:
        LongTensor: the inverse permutation, which satisfies: `inv[perm[x]] = x`.

    """
    assert perm.dim() == 1
    length = perm.size(0)
    inv = torch.zeros(length, dtype=torch.long, device=perm.device)
    inv.scatter_(0, perm, torch.arange(0, length, dtype=torch.long, device=perm.device))
    return inv.long()