from math import gcd n, m = map(int, input().split()) p = list(map(int, input().split())) c = 0 for i in range(n): if p[i] - 1 != i: c += 1 c = max(0, c - 1) if gcd(2, m) != 1: print(-1) else: n = (-c * pow(2, -1, m)) % m print((c + 2 * n))