Problem:
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

Solution in C++14 (GCC 5.4.1) (judge verdict: Wrong Answer)

#include<stdio.h>
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define f(i, x, n) for(int i = x; i < (int)n; ++i)

int an = 1, cy[100001], md = 1e9 + 7, dp[100001][2];
pair<int, int> y[100001], ln[100001];
bool vis[100001];

void no(){
	printf("0\n");
	exit(0);
}

int V;
bool go(int v, int m = 0, int d = 0){
	if (vis[v]){
		if (v == V) { ln[m].first = d; return true; }
		return false;
	}
	vis[v] = true;
	if (!y[v].first) { ln[m].second = d; return false; }
	bool k = go(y[v].first, y[v].second ? v : m, d + 1);
	if (y[v].second)ln[m].first = d, k |= go(y[v].second, v, d + 1);
	return k;
}

inline void ad(int s, int l){
	dp[0][0] = 1;
	int z = (s & 1 && s != 1) + 1;
	f(i, 1, l + 1){
		dp[i][0] = ((ll)dp[i - 1][0] * z + (ll)dp[i - 1][1] * s) % md;
		dp[i][1] = ((ll)dp[i - 1][1] * z + dp[i - 1][0]) % md;
	}
	an = (ll)an * dp[l][0] % md;
}

int main(){
	int n;
	scanf("%d", &n);
	f(i, 1, n + 1){
		int t;
		scanf("%d", &t);
		if (y[t].first){
			if (y[t].second)no();
			y[t].second = i;
		}
		else y[t].first = i;
	}
	f(i, 1, n + 1)if (y[i].second){
		V = i;
		if (!vis[i] && !go(i))no();
		if (!ln[i].second)no();
		if (ln[i].first > ln[i].second) { if ((an <<= 1) >= md)an -= md; }
		else if (ln[i].first < ln[i].second)no();
	}
	f(i, 1, n + 1)if (!vis[i]){
		V = i;
		if (go(i, i))++cy[ln[i].first];
	}
	f(i, 1, n + 1)if (cy[i])ad(i, cy[i]);
	printf("%d\n", an);
}