#include<cstdio>
#define ll long long
#define mod 1000000007
#define N 110000
int a[N],num[N],col[N],mrk[N],cnt[N],n,lng[N];
bool cir[N];
ll dp[N];
int main()
{
	scanf("%d", &n);
	ll ans=1;
	for (int i=1;i<=n;++i)
	{
		scanf("%d", &a[i]);
		++num[a[i]];
	}
	for (int i = 1; i <= n; i++)
	{
		if (col[i])
			continue;
		int x = i;
		for (; !col[x]; x = a[x])
			col[x] = i;
		if (col[x] != i)
			continue;
		for (;!cir[x];x=a[x])
			cir[x]=1;
	}
	for (int i = 1; i <= n; i++)
		if ((cir[i]&&num[i]>2)||(!cir[i]&&num[i]>1)) {printf("0");return 0;}
	for (int i=1;i<=n;++i){
		if (num[i]) continue;int x=i,tmp=0;
		while(!cir[x]) x=a[x],tmp++;lng[x]=tmp;
	}
	for (int i=1;i<=n;++i){
		if (!cir[i]) continue;int x=i,st=0,first=0,id=0,len=0;
		while (cir[x]){
			++id;cir[x]=0;
			if (lng[x]){
				if (!first){
					st=first=id;len=lng[x];x=a[x];continue;
				}else{
					int numm=(lng[x]<(id-st))+(lng[x]<=(id-st));
					(ans*=numm)%=mod;if (!ans) {printf("0");return 0;}st=id;x=a[x];continue;
				}
			}x=a[x];
		}if (first){
			int numm=(len<(id+first-st))+(len<=(id+first-st));
			(ans*=numm)%=mod;if (!ans) {printf("0");return 0;}
		}else cnt[id]++;
	}
	for (int i=1;i<=n;++i){
		dp[0]=1;if (!cnt[i]) continue;
		if (i>1&&(i%2)){
			for (int j=1;j<=cnt[i];++j) {
				dp[j]=dp[j-1]*2%mod;if (j>1) (dp[j]+=dp[j-2]*(j-1)*i%mod)%=mod;
			}
		}else{
			for (int j=1;j<=cnt[i];++j){
				dp[j]=dp[j-1];if (j>1) (dp[j]+=dp[j-2]*(j-1)*i%mod)%=mod;
			}
		}
		(ans*=dp[cnt[i]])%=mod;if (!ans){printf("0");return 0;}
	}printf("%lld",ans);
	return 0;
}
