from math import gcd MOD = 1000000007 N, M = map(int, input().split()) A = [int(s) - 1 for s in input().split()] used = [False] * N cycles = [0] * (N+1) for i in range(N): if used[i]: continue cnt = 0 while not used[i]: used[i] = True i = A[i] cnt += 1 cycles[cnt] += 1 fact = [0] * (N+1) ifact = [0] * (N+1) fact[0] = 1 ifact[0] = 1 for i in range(N): fact[i+1] = fact[i] * (i+1) % MOD ifact[i+1] = pow(fact[i+1], MOD - 2, MOD) def binom(n, k): return fact[n] * ifact[k] % MOD * ifact[n-k] % MOD ans = 1 for i in range(1, N+1): dp = [0] * (cycles[i] + 1) ms = [m for m in range(1, N+1) if m // gcd(m, M) == i] dp[0] = 1 for j in range(1, cycles[i] + 1): for m in ms: if j - m//i >= 0: dp[j] += dp[j - m//i] * binom(j-1, m//i - 1) % MOD * fact[m//i - 1] % MOD * pow(i, m//i - 1, MOD) % MOD dp[j] %= MOD ans = ans * dp[cycles[i]] % MOD print(ans)