#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <cmath>

using namespace std;

const int MAXN = 100000 + 1000;
const int MOD = 1000000000 + 7;
const int INF = 0x1f1f1f1f;

int n, p[MAXN];
int ans = 1;
vector<int> redg[MAXN];
vector<int> vc, vl;
bool vis[MAXN], onc[MAXN];
int cnt[MAXN], f[MAXN];

int get_len(int x)
{
	vis[x] = true;
	int ret = 0;
	for(int i = 0; i < redg[x].size(); i++)
		if(!onc[redg[x][i]])
			ret = ret == 0 ? get_len(redg[x][i]) + 1 : -INF;
	return ret;
}

int find_circle(int x)
{
	vis[x] = true;
	int y = p[x], t = vis[y] ? y : find_circle(y);
	if(t)
		onc[x] = true, vc.push_back(x);
	return t == x ? 0 : t;
}

void work()
{
	for(int i = 1; i <= n; i++)
		redg[p[i]].push_back(i);
	for(int i = 1; i <= n; i++)
		if(!vis[i])
		{
			vc.clear(), vl.clear();
			find_circle(i);	
			reverse(vc.begin(), vc.end());
			int last = -1;
			for(int j = 0; j < vc.size(); j++)
			{
				int x = vc[j], t = get_len(x);
				if(t < 0)
				{
					ans = 0; return ;
				}
				else if(t > 0)
					last = j;
				vl.push_back(t);
				// cerr << vc[j] << ' ' << vl[j] << endl;
			}
			// cerr << endl;
			if(last < 0)
			{
				cnt[vc.size()]++;
				continue;
			}
			else
			{
				for(int j = 0; j < vc.size(); j++)
					if(vl[j] > 0)
					{
						int l1 = vl[j], l2 = (j - last + vc.size() - 1) % vc.size() + 1;
						// cerr << l1 << ' ' << l2 << endl;
						if(l1 < l2)
							ans = (ans * 2) % MOD;
						else if(l1 == l2)
							ans = (ans * 1) % MOD;
						else
							ans = 0;
						last = j;
					}
			}
		}
	for(int i = 1; i <= n; i++)
		if(cnt[i])
		{
			int lam = (i == 1 || i % 2 == 0 ? 1 : 2);
			f[0] = 1;
			for(int j = 1; j <= cnt[i]; j++)
			{
				f[j] = (long long)f[j - 1] * lam % MOD;
				if(j - 2 >= 0)
					f[j] = (f[j] + (long long)f[j - 2] * (j - 1) % MOD * i) % MOD;
			}
			ans = (long long)ans * f[cnt[i]] % MOD;
		}
}

int main()
{
	ios::sync_with_stdio(false);
	// freopen("1.in", "r", stdin);
	// freopen("1.out", "w", stdout);

	cin >> n;
	for(int i = 1; i <= n; i++)
		cin >> p[i];

	work();
	cout << ans << endl;


	return 0;
}
