#include<cstdio>
#define ll long long
#define P 1000000007
int a[100005],in[100005],col[100005],cnt[100005],n,L[100005];bool cir[100005];long long f[100005],ans=1;
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;++i) scanf("%d",&a[i]),++in[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]&&in[i]>2)||(!cir[i]&&in[i]>1)) return puts("0"),0;
	for(int i=1;i<=n;++i){if(in[i]) continue;int x=i,tmp=0;while(!cir[x]) x=a[x],tmp++;L[x]=tmp;} 
	for(int i=1;i<=n;++i)
	{
		if(!cir[i]) continue;int x=i,st=0,fir=0,id=0,len=0;
		while(cir[x])
		{
			++id;cir[x]=0;
			if(L[x])
			{
				if(!fir){st=fir=id;len=L[x];x=a[x];continue;}
				else{(ans*=(L[x]<(id-st))+(L[x]<=(id-st)))%=P;if(!ans)return puts("0"),0;st=id;x=a[x];continue;}
			}
			x=a[x];
		}
		if(fir){(ans*=(len<(id+fir-st))+(len<=(id+fir-st)))%=P;if(!ans)return puts("0"),0;}
		else cnt[id]++;
	}
	for(int i=1;i<=n;++i)
	{
		f[0]=1;if(!cnt[i]) continue;
		if(i>1&&(i%2)) for(int j=1;j<=cnt[i];++j) {f[j]=f[j-1]*2%P;if(j>1) (f[j]+=f[j-2]*(j-1)*i%P)%=P;}
		else for(int j=1;j<=cnt[i];++j){f[j]=f[j-1];if(j>1) (f[j]+=f[j-2]*(j-1)*i%P)%=P;}   
		(ans*=f[cnt[i]])%=P;if(!ans)return puts("0"),0;
	}
	printf("%lld",ans);
}