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<bits/stdc++.h>
#define ll long long
#define rg register
using namespace std;
const int Mod=1e9+7;
const int MAXN=1e5+10;
int n,Ans=1,A[MAXN],Deg[MAXN],Vis[MAXN],Inc[MAXN],Fl[MAXN];
int Cs[MAXN],Dp[MAXN];
inline int Read()
{   rg int a=0,c=1;   rg char b=getchar();
	while(b!='-'&&(b<'0'||b>'9'))b=getchar();
	if(b=='-')c=-1,b=getchar();
	while(b>='0'&&b<='9')a=a*10+b-48,b=getchar();
	return a*c;
}
inline void Calc(rg int Np)
{   rg int Fd=-1,Ld=0,Nd=0,Lf=0;
	for(;Inc[Np];Inc[Np]=0,Np=A[Np],Nd++)
		if(Fl[Np]) Fd!=-1?Ans=1ll*Ans*((Fl[Np]<Nd-Ld)+(Fl[Np]<=Nd-Ld))%Mod:(Fd=Nd,Lf=Fl[Np]),Ld=Nd;
	Fd!=-1?Ans=1ll*Ans*((Lf<Fd+Nd-Ld)+(Lf<=Fd+Nd-Ld))%Mod:Cs[Nd]++;
}
int main()
{   n=Read();
	for(rg int i=1;i<=n;i++) A[i]=Read(),Deg[A[i]]++;
	for(rg int i=1,Pos;i<=n;i++)
	{   if(Vis[i]) continue ;
		for(Pos=i;!Vis[Pos];Pos=A[Pos]) Vis[Pos]=1;
		if(Pos==i) while(!Inc[Pos]) Inc[Pos]=1,Pos=A[Pos];
	}
	for(rg int i=1;i<=n;i++) if(Deg[i]-Inc[i]>1) return puts("0"),0;
	for(rg int i=1,Pos,Nl;i<=n;i++,Fl[Pos]=Nl)
		for(Pos=i,Nl=0;!Inc[Pos]&&!Deg[i];Pos=A[Pos]) Nl++;
	for(rg int i=1;i<=n;i++) if(Inc[i]) Calc(i);
	for(rg int i=1;i<=n;i++)
	{	if(!Cs[i]) continue ;   Dp[0]=1;
		for(rg int j=1;j<=Cs[i];j++)
		{   Dp[j]=(i>1&&i&1?2:1)*Dp[j-1]%Mod;
			if(j>=2) Dp[j]=(Dp[j]+1ll*Dp[j-2]*(j-1)%Mod*i)%Mod;
		}
		Ans=1ll*Ans*Dp[Cs[i]]%Mod;
	}
	printf("%d\n",Ans);
}