#include <cstdio>

typedef long long LL;
const int Mod = 1000000007;
const int MN = 100005;

int N, p[MN], c[MN], d[MN], k[MN], g[MN], Ans;
int q[MN], l, r;

int main() {
	scanf("%d", &N);
	for (int i = 1; i <= N; ++i) scanf("%d", &p[i]), ++d[p[i]];
	for (int i = 1; i <= N; ++i) if (d[i] > 2) return puts("0"), 0;
	for (int i = 1; i <= N; ++i) if (!d[i]) q[++r] = i;
	while (l < r) {
		int u = q[++l], x = p[u];
		k[x] = k[u] + 1;
		if (++c[x] == d[x]) q[++r] = x;
	}
	for (int i = 1; i <= N; ++i) if (c[i] > 1) return puts("0"), 0;
	Ans = 1;
	for (int i = 1; i <= N; ++i) if (c[i] < d[i]) {
		q[r = 1] = i;
		for (int x = p[i]; x != i; x = p[x]) q[++r] = x;
		int lst = 0;
		for (int j = 1; j <= r; ++j) if (c[q[j]]) lst = j;
		for (int j = 1; j <= r; ++j) c[q[j]] = d[q[j]];
		if (!lst) { ++g[r]; continue; }
		lst -= r;
		for (int j = 1; j <= r; ++j) if (k[q[j]]) {
			if (k[q[j]] > j - lst) return puts("0"), 0;
			if (k[q[j]] < j - lst) Ans = 2 * Ans % Mod;
			lst = j;
		}
	}
	for (int i = 1; i <= N; ++i) if (g[i]) {
		int x = 1, y = 1 + (i >= 3 && i & 1), z;
		for (int j = 2; j <= g[i]; ++j)
			z = ((1 + (i >= 3 && i & 1)) * y + (LL)x * (j - 1) * i) % Mod, x = y, y = z;
		Ans = (LL)Ans * y % Mod;
	}
	printf("%d\n", Ans);
	return 0;
}