#include<bits/stdc++.h>
using namespace std;
#define N 1111116
#define mod 1000000007

int n,a[N],d[N],h[N],g[N];
long long ans,f[N];
queue<int> q;

int read(){
	int x=0,f=1;char ch=getchar();
	for (;!isdigit(ch);ch=getchar()) if (ch=='-')  f=-f;
	for (;isdigit(ch);ch=getchar()) x=x*10+ch-'0';
	return x*f;
}

int main(){
	n=read();ans=1;
	for (int i=1;i<=n;i++) a[i]=read(),d[a[i]]++;
	for (int i=1;i<=n;i++) if (!d[i]) q.push(i);
	while (!q.empty()){
		int t=q.front();q.pop();
		if (h[a[t]]) ans=0;h[a[t]]=h[t]+1;
		if (--d[a[t]]==0) q.push(a[t]);
	}
	for (int i=1;i<=n;i++)
		if (d[i]){
			int t=i;vector<int> q;
			while (a[t]!=i&&!h[t]) t=a[t];
			while (d[t]){
				q.push_back(h[t]);
				d[t]=0;t=a[t];
			}
			if (!q[0]) g[q.size()]++;
			else {
				q.push_back(q[0]);
				for (int i=1,j=0;i<(int)q.size();i++)
					if (q[i]){
						if (q[i]<i-j) ans=ans*2%mod;
						if (q[i]>i-j) ans=0;
						j=i;
					}
			}
		}
	for (int i=1;i<=n;i++){
		f[0]=1;f[1]=(i>1&&i%2)+1;
		for (int j=2;j<=g[i];j++)
			f[j]=(f[j-1]*f[1]+f[j-2]*(j-1)*i)%mod;
		ans=(ans*f[g[i]])%mod;
	}
	printf("%lld\n",ans);return 0;
}