Next or Nextnext

AtCoder
IDagc008_e
Time2000ms
Memory256MB
Difficulty
You are given an integer sequence $a$ of length $N$. How many permutations $p$ of the integers $1$ through $N$ satisfy the following condition? * For each $1 ≤ i ≤ N$, at least one of the following holds: $p_i = a_i$ and $p_{p_i} = a_i$. Find the count modulo $10^9 + 7$. ## Constraints * $1 ≤ N ≤ 10^5$ * $a_i$ is an integer. * $1 ≤ a_i ≤ N$ ## Input The input is given from Standard Input in the following format: $N$ $a_1$ $a_2$ $...$ $a_N$ [samples]
Samples
Input #1
3
1 2 3
Output #1
4

The following four permutations satisfy the condition:

*   $(1, 2, 3)$
*   $(1, 3, 2)$
*   $(3, 2, 1)$
*   $(2, 1, 3)$

For example, $(1, 3, 2)$ satisfies the condition because $p_1 = 1$, $p_{p_2} = 2$ and $p_{p_3} = 3$.
Input #2
2
1 1
Output #2
1

The following one permutation satisfies the condition:

*   $(2, 1)$
Input #3
3
2 1 1
Output #3
2

The following two permutations satisfy the condition:

*   $(2, 3, 1)$
*   $(3, 1, 2)$
Input #4
3
1 1 1
Output #4
0
Input #5
13
2 1 4 3 6 7 5 9 10 8 8 9 11
Output #5
6
API Response (JSON)
{
  "problem": {
    "name": "Next or Nextnext",
    "description": {
      "content": "You are given an integer sequence $a$ of length $N$. How many permutations $p$ of the integers $1$ through $N$ satisfy the following condition? *   For each $1 ≤ i ≤ N$, at least one of the following",
      "description_type": "Markdown"
    },
    "platform": "AtCoder",
    "limit": {
      "time_limit": 2000,
      "memory_limit": 262144
    },
    "difficulty": "None",
    "is_remote": true,
    "is_sync": true,
    "sync_url": null,
    "sign": "agc008_e"
  },
  "statements": [
    {
      "statement_type": "Markdown",
      "content": "You are given an integer sequence $a$ of length $N$. How many permutations $p$ of the integers $1$ through $N$ satisfy the following condition?\n\n*   For each $1 ≤ i ≤ N$, at least one of the following...",
      "is_translate": false,
      "language": "English"
    }
  ]
}
Full JSON Raw Segments