E - Next or Nextnext

Time Limit: 2 sec / Memory Limit: 256 MB

### 問題文

• 1 ≤ i ≤ N について、p_i = a_i または p_{p_i} = a_i の少なくとも一方が成り立つ。

• 1 ≤ N ≤ 10^5
• a_i は整数である。
• 1 ≤ a_i ≤ N

### 入力

N
a_1 a_2 ... a_N


### 入力例 1

3
1 2 3


### 出力例 1

4


• (1, 2, 3)
• (1, 3, 2)
• (3, 2, 1)
• (2, 1, 3)

たとえば (1, 3, 2) は、p_1 = 1, p_{p_2} = 2, p_{p_3} = 3 となっています。

### 入力例 2

2
1 1


### 出力例 2

1


• (2, 1)

### 入力例 3

3
2 1 1


### 出力例 3

2


• (2, 3, 1)
• (3, 1, 2)

### 入力例 4

3
1 1 1


### 出力例 4

0


### 入力例 5

13
2 1 4 3 6 7 5 9 10 8 8 9 11


### 出力例 5

6


Score : 1400 points

### Problem Statement

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


### Output

Print the number of the permutations p that satisfy the condition, modulo 10^9 + 7.

### Sample Input 1

3
1 2 3


### Sample 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.

### Sample Input 2

2
1 1


### Sample Output 2

1


The following one permutation satisfies the condition:

• (2, 1)

### Sample Input 3

3
2 1 1


### Sample Output 3

2


The following two permutations satisfy the condition:

• (2, 3, 1)
• (3, 1, 2)

### Sample Input 4

3
1 1 1


### Sample Output 4

0


### Sample Input 5

13
2 1 4 3 6 7 5 9 10 8 8 9 11


### Sample Output 5

6