n, d = (int(x) for x in input().split())
m = int(input())
x = []
y = []
for i in range(m):
    x1,y1 = (int(x) for x in input().split())
    if (d <= x1 + y1 <= 2*n - d) and -d <= x1 - y1 <= d:
        print("YES")
    else:
        print("NO")


def F(px, py, ax, ay, bx, by):
  return (bx-ax)*(py-ay)-(by-ay)*(px-ax)

n, d = map(int, input().split())
m = int(input())
for i in range(m):
  x, y = map(int, input().split())
  if F(x, y, d, 0, n, n - d) >= 0 and F(x, y, n, n - d, n - d, n) >= 0 and F(x, y, n - d, n, 0, d) >= 0 and F(x, y, 0, d, d, 0) >= 0:
    print('YES')
  else:
    print('NO')

#(bx-ax)*(py-ay)-(by-ay)*(px-ax)


import sys
import math
import collections
import bisect
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def get_list(): return list(map(int, sys.stdin.readline().strip().split()))
def get_string(): return sys.stdin.readline().strip()
for t in range(1):
    n,d=get_ints()
    for q in range(int(input())):
        x,y=get_ints()
        if d <= x + y <= 2 * n - d and - d <= y - x <= d:
            print('YES')
        else:
            print('NO')


n, d = map(int, input().split())
m = int(input())
for i in range(m):
    x, y = map(int, input().split())
    if y <= x+d and y >= x-d and y >= d-x and y <= n + (n - d) - x:
       print("YES")
    else:
       print("NO")


n, d = map(int, input().split())
m = int(input())
def area(p):
    r = 0
    p.append(p[0])
    for i in range(len(p) - 1):
        r += (p[i + 1][0] - p[i][0]) * (p[i + 1][1] + p[i][1])
    return abs(r)
ps = [(0, d), (d, 0), (n, n - d), (n - d, n)]
for i in range(m):
    c = tuple(map(int, input().split()))
    if area([ps[0], ps[1], c]) + area([ps[1], ps[2], c]) + area([ps[2], ps[3], c]) + area([ps[3], ps[0], c]) == area(ps):
        print("YES")
    else:
        print("NO")


#
# Created by Polusummator on 24.10.2020
# --------- Little PyPy Squad ---------
# Verdict:
#
n, d = [int(i) for i in input().split()]
k0 = -1
k1 = 1
k2 = 1
k3 = -1
b0 = d
b1 = -d
b2 = d
b3 = n - d + n
m = int(input())
A = []
for _ in range(m):
    x, y = [int(i) for i in input().split()]
    if y >= k0 * x + b0 and y >= k1 * x + b1 and y <= x * k2 + b2 and y <= k3 * x + b3:
        A.append('YES')
    else:
        A.append('NO')
for i in A:
    print(i)


n,d = map(int,input().split())
f = lambda x,y : (x+y-d)*(y-x-d)*(y-x+d)*(y+x+d-2*n)
tc = int(input())
while tc!=0:
    tc-=1
    x,y = map(int,input().split())
    # print(x + " "+ y)/
    flag = False
    if f(n/2,n/2) >= 0:
        Flag = True

    if(flag):
        if f(x,y) <= 0:
            print("YES")
        else :
            print("NO")
    else :
        if f(x,y) >= 0:
            print("YES")
        else :
            print("NO")


def arr_inp():
    return [int(x) for x in stdin.readline().split()]

from sys import stdin

n, d = arr_inp()
for i in range(int(input())):
    x, y = arr_inp()
    mi, ma = d - x, n - d
    if x > d:
        mi = x - d
    if x <= ma:
        ma = d + x
    else:
        ma = n - (x - ma)
    print('YES' if y >= mi and y <= ma else 'NO')


n, d = [int(i) for i in input().split()]

'''
 y = -x + d
 y = x - d
 y = x + d
 y = -x + 2n - d
'''

k = int(input())
z = []
for i in range(k):
    x, y = [int(i) for i in input().split()]
    z.append((x, y))

for x, y in z:
    b1 = y >= -x + d
    b2 = y >= x - d
    b3 = y <= x + d
    b4 = y <= -x + 2*n - d
    if b1 and b2 and b3 and b4:
        print("YES")
    else:
        print("NO")


n,d = int(input()), int(input())
rect = [[0,d],[d,0],[n,n-d],[n-d,n]]
m = int(input())
for i in range(m):
    x,y = int(input()),int(input())
    if (y <= x + d) and (y >= x - d) and (y >= -x + d) and ( y <= -x +n+n-d):
        print("YES")
    else:
        print("NO")


n,d = input().split()
n = int(n)
d = int(d)
rect = [[0,d],[d,0],[n,n-d],[n-d,n]]
m = int(input())
for i in range(m):
    x,y = input().split()
    x = int(x)
    y = int(y)
    if (y <= x + d) and (y >= x - d) and (y >= -x + d) and ( y <= -x +n+n-d):
        print("YES")
    else:
        print("NO")


n, d = map(int, input().split())
m = int(input())
for _ in range(m):
    x, y = map(int, input().split())
    print('YES' if abs(x - y) <= d and abs(x + y - n) < n - d else 'NO')


n, d = map(int, input().split())
m = int(input())
for _ in range(m):
    x, y = map(int, input().split())
    print('YES' if abs(x - y) <= d and abs(x + y - n) <= n - d else 'NO')


n,d=map(int,input().split())

for _ in range(int(input())):
    x,y=map(int,input().split())
    if d<=x+y<=2*n-d and -d<=x-y<=d:
        print("YES")
    else:
        print("NO")


'''input
8 7
4
4 4
2 8
8 1
6 1
'''
from sys import stdin, stdout
def myfunction(x, y, n, d):
	if ((y+x) >= d) and ((y+x) <= (2*n - d)) and ((x-y) <= d) and ((y-x) <= d):
		return "YES\n"
	else:
		return "NO\n"
n, d = list(map(int, stdin.readline().split()))
m = int(stdin.readline())
for i in range(m):
	x, y = list(map(int, stdin.readline().split()))
	stdout.write(myfunction(x, y, n, d))


n,d=map(int,input().split())
m=int(input())
for i in range(m):
    x,y=map(int,input().split())

    if (x+y)>=d and (x+y)<=2*n-d and (x-y)<=d and (x-y)>=-d:
        print('YES')
    else:
        print('NO')


inhalf  = lambda A,B,C,p: (A*p[0]+B*p[1]+C)>=0
inR     = lambda n,d,p: inhalf(1,1,-d,p) and inhalf(-1,-1,(n<<1)-d,p) and inhalf(1,-1,d,p) and inhalf(-1,1,d,p)
n,d     =  list(map(int,input().split())) #100
ps      = [list(map(int,input().split())) for i in range(int(input()))]
[print('YES' if inR(n,d,p) else 'NO') for p in ps]


#Выпуклый многоугольник, по каждой стороне:
# D = (x2 - x1) * (yp - y1) - (xp - x1) * (y2 - y1)
# D > 0 : dot on the left
# D < 0 : dot on the right
# D = 0 : dot on the line

def D(p1, p2, pc):
	x1, y1 = p1
	x2, y2 = p2
	xp, yp = pc
	return (x2 - x1) * (yp - y1) - (xp - x1) * (y2 - y1)

n, d = [int(i) for i in input().split()]
one = (0, d); two = (n-d, n)
three = (n, n-d); four = (d, 0)
cnt = int(input())
ans = []
for _ in range(cnt):
	x, y = [int(i) for i in input().split()]
	p1 = D(one, two, (x, y))
	p2 = D(two, three, (x, y))
	p3 = D(three, four, (x, y))
	p4 = D(four, one, (x, y))
	if p1 <= 0 and p2 <= 0 and p3 <= 0 and p4 <= 0:
		ans.append('YES')
	else:
		ans.append('NO')

print(*ans, sep='\n')


[n, d] = map(int, input().split())
m = int(input())
gh = []
cohor = [1,2]
for i in range(m):
    cohor = list(map(int, input().split()))
    gh.append(cohor)
for i in gh:
    if (i[0]+i[1] >= d) & (i[0] + i[1] <= 2*n-d) & (abs(i[0]-i[1]) <= d):
        print("YES")
    else:
        print("NO")


n, d = [int(s) for s in input().split(' ')]
m = int(input())
for g in range(m):
    x, y = [int(s) for s in input().split(' ')]
    if d <= x + y <= 2 * n - d and - d <= y - x <= d:
        print('YES')
    else:
        print('NO')


n, d = [int(s) for s in input().split(' ')]
m = int(input())
for g in range(m):
    x, y = [int(s) for s in input().split(' ')]
    if d <= max(x, y) <= n and abs(x - y) <= d:
        print('YES')
    else:
        print('NO')


n,d=map(int,input().split())
for i in range(int(input())):
    x,y=map(int,input().split())
    if (d<= x+y <=2*n-d) and (-d<= x-y <= d):
        print("YES")
    else:
        print("NO")


n, d = map(int, input().split())
m = int(input())
for i in range(m):
    x, y = map(int, input().split())
    if (y >= x - d and y <= x + d and y >= -x + d and y <= -x + 2 * n - d):
        print("YES")
    else:
        print("NO")


n, d = map(int, input().split())
m = int(input())
for i in range(m):
    x, y = map(int, input().split())
    if (y >= x - d and y <= x + 2 * d and y >= -x + d and y <= -x + 2 * n - d):
        print("YES")
    else:
        print("NO")


n, d = map(int, input().split())
m = int(input())
k = []
for i in range(m):
    k.append(list(map(int, input().split())))
ans = [0] * m
up = d
down = d
if n-d >= d:
    for x in range(n+1):
        for i in range(m):
            if k[i][0] == x and down <= k[i][1] <= up:
                ans[i] = 1
        if x < min(n-d, d):
            up += 1
            down -=1
        elif x < n - min(n-d, d):
            up += 1
            down += 1
        else:
            up -= 1
            down += 1
else:
    for x in range(n+1):
        for i in range(m):
            if k[i][0] == x and down <= k[i][1] <= up:
                ans[i] = 1
        if x < min(n-d, d):
            up += 1
            down -=1
        elif x < n-  min(n-d, d):
            up -= 1
            down -= 1
        else:
            up -= 1
            down += 1

for i in ans:
    if i:
        print("YES")
    else:
        print("NO")


coor = input().split()
coor = [int(num) for num in coor]

GrassHopper = []
n = int(input())

Pos = []

for i in range(n):
    points = input().split()
    points = [int(num) for num in points]

    GrassHopper.append(points)

Line1 = coor[1]
Line2 = coor[1]
Line3 = coor[0] * 2 - coor[1]
Line4 = -coor[1]

i = 0
for point in GrassHopper:
    j = 0
    addi = point[0] + point[1]
    subs = point[0] - point[1]

    if addi >= Line2 and addi <= Line3:
        if subs >= Line4 and subs <= Line1:
            j = 1
            Pos.append('YES')

    if not j:
        Pos.append('NO')

for pos in Pos:
    print(pos)


n,d = map(int,input().split())
q = int(input())
s1 = [0,d]
s2 = [d,0]
s3 = [n,n-d]
s4 = [n-d,n]

for i in range(q):
    x,y = map(int,input().split())
    if(x-y+d>0 and x-y-d>0):
        print('NO')
    elif(x-y+d<0 and x-y-d<0):
        print('NO')
    elif(x+y-d>0 and x+y-2*n+d>0):
        print('NO')
    elif(x+y-d<0 and x+y-2*n+d<0):
        print('NO')
    else:
        print('YES')


import sys

def judge(x, y):
    if y >= -1 * x + d and y <= -1 * x + 2 * n - d and y >= x - d and y <= x + d:
        return True
    return False

n, d = map(int, sys.stdin.readline().split())
a = int(sys.stdin.readline())
for _ in range(a):
    x, y = map(int, sys.stdin.readline().split())
    if judge(x, y):
        print('YES')
    else:
        print('NO')


import math
import sys
inf = 2000000000

class Point:
    x, y = 0, 0

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, vec):  # point + VECTOR
        return Point(self.x + vec.x, self.y + vec.y)

    def __sub__(self, vec):  # point - VECTOR
        self.x -= vec.x
        self.y -= vec.y

    def __str__(self):
        return str(self.x) + ' ' + str(self.y)

    def dist_to_point(self, pA):
        return vector_by_points(self, pA).length()

    def dist_to_line(self, line):
        if math.sqrt(line.a * line.a + line.b * line.b) == 0:
            return inf
        return (self.x * line.a + self.y * line.b + line.c) / math.sqrt(line.a * line.a + line.b * line.b)

    def dist_to_segment(self, pA, pB):
        AB = vector_by_points(pA, pB)
        AC = vector_by_points(pA, self)
        if AB * AC < 0:  # this means angle CAB > 90
            return self.dist_to_point(pA)
        BA = -AB
        BC = vector_by_points(pB, self)
        if BA * BC < 0:  # this means angle CBA > 90
            return self.dist_to_point(pB)
        return abs(self.dist_to_line(line_by_points(pA, pB)))

    def dist_to_ray(self, pA, pB):
        AC = vector_by_points(pA, self)
        AB = vector_by_points(pA, pB)
        if AC * AB < 0:
            return self.dist_to_point(pA)
        return abs(self.dist_to_line(line_by_points(pA, pB)))

class Vector:
    x, y = 0, 0

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def length(self):  # |vector|
        return math.sqrt(self.x * self.x + self.y * self.y)

    def __mul__(self, vec):  # scalar multiplication
        return self.x * vec.x + self.y * vec.y

    def __pow__(self, vec):  # vector multiplication
        return self.x * vec.y - self.y * vec.x

    def __truediv__(self, x):  # vector / number
        return Vector(self.x / x, self.y / x)

    def __add__(self, vec):  # vector1 + vector2
        return Vector(self.x + vec.x, self.y + vec.y)

    def __sub__(self, vec):  # vector1 - vector2
        return Vector(self.x - vec.x, self.y - vec.y)

    def __neg__(self):  # -vector
        return Vector(-self.x, -self.y)

    def __str__(self):
        return str(self.x) + ' ' + str(self.y)

    def normalize(self):  # vector / |vector|
        ln = self.length()
        self.x /= ln
        self.y /= ln

    def to_len(self, x):
        self.normalize()
        self.x *= x
        self.y *= x

    def angle_rad(self, vec):
        angle = math.atan2(self ** vec, self * vec)
        if angle < 0:
            angle += 2 * math.pi
        return angle

    def angle(self, vec):
        return self.angle_rad(vec) / math.pi * 180

    def polar(self):
        return self.angle_rad(Vector(1, 0))

class Line:
    a, b, c = 0, 0, 0

    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    def __str__(self):
        return str(self.a) + ' ' + str(self.b) + ' ' + str(self.c)

    def normalize(self):
        z = math.sqrt(self.a * self.a + self.b * self.b)
        self.a /= z
        self.b /= z
        self.c /= z

    def intersection(self, ln):
        opred = self.a * ln.b - self.b * ln.a
        opred_x = self.c * ln.b - self.b * ln.c
        opred_y = self.a * ln.c - self.c * ln.a
        x = -opred_x / opred
        y = -opred_y / opred
        return Point(x, y)

def vector_by_points(p1, p2):
    return Vector(p2.x - p1.x, p2.y - p1.y)

def normal_to_line(line):
    return Vector(line.a, line.b)

def line_by_points(p1, p2):
        b = p1.x - p2.x
        a = p2.y - p1.y
        c = -(a * p1.x + b * p1.y)
        return Line(a, b, c)

def segment_intersect(pA, pB, pC, pD):  # does AB intersect CD?
    AB = vector_by_points(pA, pB)
    AC = vector_by_points(pA, pC)
    AD = vector_by_points(pA, pD)
    CD = vector_by_points(pC, pD)
    CB = vector_by_points(pC, pB)
    CA = -AC
    if (AB ** AC) * (AB ** AD) <= 0 and (CD ** CB) * (CD ** CA) <= 0 and (min(pC.x, pD.x) <= max(pA.x, pB.x) <= max(pC.x, pD.x) or min(pA.x, pB.x) <= max(pC.x, pD.x) <= max(pA.x, pB.x)):
        return True
    return False

def segment_to_segment(pA, pB, pC, pD):
    if segment_intersect(pA, pB, pC, pD):
        return 0
    mn = min(pA.dist_to_segment(pC, pD), pB.dist_to_segment(pC, pD))
    mn = min(mn, pC.dist_to_segment(pA, pB))
    mn = min(mn, pD.dist_to_segment(pA, pB))
    return mn

def ray_to_ray(pA, pB, pC, pD):
    pt = line_by_points(pA, pB).intersection(line_by_points(pC, pD))
    if pt.dist_to_ray(pA, pB) == 0 and pt.dist_to_ray(pC, pD) == 0:
        return 0
    return min(pA.dist_to_ray(pC, pD), pC.dist_to_ray(pA, pB))

def area(a):  # a is list of Points (shape not necessary convex)
    prev = Vector(a[-1].x, a[-1].y)
    ans = 0
    for pt in a:
        cur = Vector(pt.x, pt.y)
        ans += prev ** cur / 2
        prev = cur
    return abs(ans)

n, d = map(int, input().split())
field = [Point(0, d), Point(d, 0), Point(n, n - d), Point(n - d, n)]
s = area(field)
q = int(input())
for i in range(q):
    x, y = map(int, input().split())
    cur = Point(x, y)
    ar = area([field[0], field[1], cur]) + area([field[1], field[2], cur]) + area([field[2], field[3], cur]) + area([field[3], field[0], cur])
    if ar == s:
        print('YES')
    else:
        print('NO')


n, d = map(int, input().split())
m = int(input())
for i in range(m):
    x, y = map(int, input().split())
    t1, t2, t3, t4 = False, False, False, False
    if x+y>=d: t1 = True
    if y+n-x>=n-d: t2 = True
    if x+n-y>=n-d: t3 = True
    if n-x+n-y>=d: t4 = True
    if t1 and t2 and t3 and t4: print('YES')
    else: print('NO')


n,d=map(int,input().split())
m=int(input())
for i in range(m):
    x,y=map(int,input().split())
    if x-y-d<=0 and x-y+d>=0 and x+y-d>=0 and x+y-2*n+d<=0:
        print("YES")
    else:
        print("NO")


n,d=map(int,input().split())
m=int(input())
for i in range(n):
    x,y=map(int,input().split())
    if x-y-d<=0 and x-y+d>=0 and x+y-d>=0 and x+y-2*n+d<=0:
        print("YES")
    else:
        print("NO")


import math,sys,bisect,heapq
from collections import defaultdict,Counter,deque
from itertools import groupby,accumulate
#sys.setrecursionlimit(200000000)
int1 = lambda x: int(x) - 1
import numpy as np
#input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda: map(int,input().split())
alele = lambda: list(map(int, input().split()))
ilelec = lambda: map(int1,input().split())
alelec = lambda: list(map(int1, input().split()))
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
#MOD = 1000000000 + 7
def Y(c):  print(["NO","YES"][c])
def y(c):  print(["no","yes"][c])
def Yy(c):  print(["No","Yes"][c])

n,d = ilele()
for _ in range(int(input())):
    x,y = ilele()
    Y((d <= x +y <= 2*n - d) and (-d <= x-y <= d))


import math,sys,bisect,heapq
from collections import defaultdict,Counter,deque
from itertools import groupby,accumulate
#sys.setrecursionlimit(200000000)
int1 = lambda x: int(x) - 1
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda: map(int,input().split())
alele = lambda: list(map(int, input().split()))
ilelec = lambda: map(int1,input().split())
alelec = lambda: list(map(int1, input().split()))
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
#MOD = 1000000000 + 7
def Y(c):  print(["NO","YES"][c])
def y(c):  print(["no","yes"][c])
def Yy(c):  print(["No","Yes"][c])

n,d = ilele()
for _ in range(int(input())):
    x,y = ilele()
    Y((d <= x +y <= 2*n - d) and (-d <= x-y <= d))


n, d = map(int, input().split())
A = (0, d)
B = (d, 0)
C = (n-d, n)
D = (n, n-d)

def cross2(A, B):
	return A[0]*B[1] - A[1]*B[0]

def cross(p, A, B):
	return cross2(A, B) - cross2(A, p) - cross2(p, B)

def inTri(p, A, B, C):
	s1 = cross(p, A, B)
	s2 = cross(p, B, C)
	s3 = cross(p, C, A)
	if s1 == 0 or s2 == 0 or s3 == 0: return True
	if s1 > 0 and s2 > 0 and s3 > 0: return True
	return s1 < 0 and s2 < 0 and s3 < 0

m = int(input())
ans = ["" for i in range(m)]
for i in range(m):
	p = tuple(map(int, input().split()))
	ans[i] = "YES" if inTri(p, A, B, C) or inTri(p, D, B, C) else "NO"

print("\n".join(ans))


import sys
input=sys.stdin.buffer.readline

n,d=map(int,input().split())
m=int(input())
while m:
	m-=1
	x,y=map(int,input().split())
	e1=x+y-d
	e2=x-y-d
	e3=x+y-2*n+d
	e4=y-d-x
	if e1==0 or e2==0 or e3==0 or e4==0:
		print("YES")
	else:
		if e1>0 and e2<0 and e3<0 and e4<0:
			print("YES")
		else:
			print("NO")
						#unknown_2433


n, d = map(int, input().split())
m = int(input())

def f(x):
    return -abs(x - (n - d)) + n

def g(x):
    return abs(x - d)

ok = True

for _ in range(m):
    x, y = map(int, input().split())

    if y <= f(x) and y >= g(x):
        print("YES")
    else:
        print("NO")


def pr(x, y):
	if (x - xx[0]) * (yy[3] - yy[0]) >= (y - yy[0]) * (xx[3] - xx[0]):
		 fl = True
	if (x - xx[0]) * (yy[1] - yy[0]) <= (y - yy[0]) * (xx[1] - xx[0]) and fl:
		fl = True
	else:
		fl = False
	if (x - xx[1]) * (yy[2] - yy[1]) >= (y - yy[1]) * (xx[2] - xx[1]) and fl:
		fl = True
	else:
		fl = False
	if (x - xx[2]) * (yy[3] - yy[2]) <= (y - yy[2]) * (xx[3] - xx[2]) and fl:
		return "NO"
	return "YES"

n, d = map(int, input().split())
a = [0,d,d,0,n,n - d,n - d, n]
xx = a[::2]
k = int(input())
yy = a[1::2]
print(xx, yy)
for i in range(k):
	x1, y1 = map(int,input().split())
	print(pr(x1, y1))


n,d=list(map(int,input().split()))

for i in range(int(input())):
    x,y=list(map(int,input().split()))
    a=0

    if x+y>= d:
        a+=1
    if n-(y-x) >= n-d:
        a+=1
    if n-(x-y) >= n-d:
        a+=1
    if 2*n -(x+y) >= d:
        a+=1

    if a==4:
        print('YES')
    else:
        print('NO')


n, d = map(int, input().split())
m = int(input())
h = []
for i in range(m):
    x, y = map(int, input().split())
    if y >= -x + d and y >= x - d and y <= x + d and y <= -x + 2*n - d:
        print('YES')
    else:
        print('NO')


class Line:
    def __init__(self, px0, py0, px1, py1):
        self.px0, self.py0, self.px1, self.py1 = px0, py0, px1, py1

    def is_on_line(self, x, y):
        x0, y0 = self.px0 - x, self.py0 - y
        x1, y1 = self.px1 - x, self.py1 - y
        return x0 * y1 == x1 * y0 and x0 * x1 <= 0

    def is_on_top(self, x, y):
        return y > self.py0 + (x - self.px0) * (self.py1 - self.py0) / (self.px1 - self.px0)

    def is_on_right(self, x, y):
        return x > self.px0 + (y - self.py0) * (self.px1 - self.px0) / (self.py1 - self.py0)

if __name__ == "__main__":
    n, d = tuple(map(int, input().split()))
    m = int(input())
    lines = (Line(0, d, d, 0), Line(d, 0, n, n - d),
             Line(n, n - d, n - d, n), Line(n - d, n, 0, d),)

    while m:
        m -= 1
        x, y = tuple(map(int, input().split()))
        for ln in lines:
            if ln.is_on_line(x, y):
                print('YES')
                break
        else:
            if lines[0].is_on_right(x, y) and lines[0].is_on_top(x, y) and \
                    not lines[1].is_on_right(x, y) and lines[1].is_on_top(x, y) and \
                    not lines[2].is_on_right(x, y) and not lines[2].is_on_top(x, y) and \
                    lines[3].is_on_right(x, y) and not lines[3].is_on_top(x, y):
                print('YES')
            else:
                print('NO')


n, d = map(int, input().split())
m = int(input())

for i in range(m):
	x, y = map(int, input().split())
	if x-y+d >= 0 and x-y-d<= 0 and x+y >= d and x+y <= 2*n-d:
		print("YES")
	else:
		print("NO")


n, d = map(int, input().split())
m = int(input())

for i in range(m):
	x, y = map(int, input().split())
	if x-y+d >= 0 and x-y-d<= 0:
		print("YES")
	else:
		print("NO")


def prm(x, y, xv, yv):
   ch=0
   for i in range(len(xv)):
      if (((yv[i]<=y and y<=yv[i-1]) or (yv[i-1]<=y and y<=yv[i])) and (x >= (xv[i-1] - xv[i]) * (y - yv[i]) / (yv[i-1] - yv[i]) + xv[i])):
         ch = 1 - ch
   return ch
Listx=["#"]
Listy=["#"]
n, d = map(int, input().split())
a = int(input())
for i in range(a):
   x, y = map(int, input().split())
   Listx.append(x)
   Listy.append(y)
for i in range(1,a+1):
   if  prm(Listx[i], Listy[i], (0, d, n, n-d), (d, 0, n-d, n))==1 :
      print("YES")
   else:
      print("NO")


Listx=["#"]
Listy=["#"]
n, d = map(int, input().split())
a = int(input())
for i in range(a):
   x, y = map(int, input().split())
   Listx.append(x)
   Listy.append(y)
for i in range(1,a+1):
   x1=Listx[i]
   y1=Listy[i]
   if  y1-d<=x1 and x1-d<=y1 and x1+y1>=d and x1+y1<=2*n-d:
      print("YES")
   else:
      print("NO")


#include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define X first
#define Y second
#define fill(A,B) memset(A,B,sizeof(A))
#define For(i,A,B) for(int i=(A);i<(int)(B);i++)
#define rep(i,A,B) for(int i=(A);i<=(B);i++)
#define dep(i,B,A) for(int i=(B);i>=(A);i--)
#define re(i,A) for(int i=0;i<(int)(A);i++)
#define de(i,A) for(int i=(A)-1;~i;i--)
#define inf (1LL<<62)
#define mn 777
#define P 1000000007
#define si(x) ((int)x.size())
#define MAX(A,B) A=max(A,B)
#define MIN(A,B) A=min(A,B)
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
inline ll pow(ll a,int b){ll tmp=1;for(;b;b>>=1){if(b&1)tmp=(ll)tmp*a%P;a=(ll)a*a%P;}return tmp;}
template<class T>inline void R(T &xx){xx=0;char ch=getchar();bool F=0;while((ch<'0'||ch>'9')&&ch!='-')ch=getchar();if(ch=='-')F=1,ch=getchar();while(ch>='0'&&ch<='9')xx=xx+xx+(xx<<3)+ch-48,ch=getchar();if(F)xx=-xx;}

queue<int>q;
int n,m,p,x,y;vector<int>s,t,g[mn];
int in[mn],out[mn];
ll d[mn][mn],f[mn][mn],ans=1;
int main(){
#ifndef ONLINE_JUDGE
    freopen("1.in","r",stdin);
    //freopen("2.out","w",stdout);
#endif
    R(n),R(m),R(p);
    re(i,m){
        R(x),R(y);
        g[x].pb(y);in[y]++;out[x]++;
    }
    rep(i,1,n){
        if(!in[i])s.pb(i);
        if(!out[i])t.pb(i);
    }int N=si(s);
    re(i,N)d[s[i]][s[i]]=1,q.push(s[i]);
    for(int x,y;si(q);){
        x=q.front();q.pop();
        re(i,si(g[x])){
            y=g[x][i];
            if(!--in[y])q.push(y);
            re(j,N)(d[s[j]][y]+=d[s[j]][x])%=p;
        }
    }
    re(i,N)re(j,N)f[i][j]=d[s[i]][t[j]];
    re(i,N){
        For(j,i+1,N)while(f[j][i]){
            ll l=f[i][i]/f[j][i];
            For(k,i,N)(f[i][k]-=l*f[j][k])%=p;
            For(k,i,N)swap(f[i][k],f[j][k]);
            ans*=-1;
        }
        (ans*=f[i][i])%=p;if(ans<0)ans+=p;
    }cout<<(ans+p)%p<<endl;
    return 0;
}


#include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define X first
#define Y second
#define fill(A,B) memset(A,B,sizeof(A))
#define For(i,A,B) for(int i=(A);i<(int)(B);i++)
#define rep(i,A,B) for(int i=(A);i<=(B);i++)
#define dep(i,B,A) for(int i=(B);i>=(A);i--)
#define re(i,A) for(int i=0;i<(int)(A);i++)
#define de(i,A) for(int i=(A)-1;~i;i--)
#define inf (1LL<<62)
#define mn 777
#define P 1000000007
#define si(x) ((int)x.size())
#define MAX(A,B) A=max(A,B)
#define MIN(A,B) A=min(A,B)
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
inline ll pow(ll a,int b){ll tmp=1;for(;b;b>>=1){if(b&1)tmp=(ll)tmp*a%P;a=(ll)a*a%P;}return tmp;}
template<class T>inline void R(T &xx){xx=0;char ch=getchar();bool F=0;while((ch<'0'||ch>'9')&&ch!='-')ch=getchar();if(ch=='-')F=1,ch=getchar();while(ch>='0'&&ch<='9')xx=xx+xx+(xx<<3)+ch-48,ch=getchar();if(F)xx=-xx;}

queue<int>q;
int n,m,p,x,y;vector<int>s,t,g[mn];
int in[mn],out[mn];
ll d[mn][mn],f[mn][mn],ans;
int main(){
#ifndef ONLINE_JUDGE
    freopen("1.in","r",stdin);
    //freopen("2.out","w",stdout);
#endif
    R(n),R(m),R(p);
    re(i,m){
        R(x),R(y);
        g[x].pb(y);in[y]++;out[x]++;
    }
    rep(i,1,n){
        if(!in[i])s.pb(i);
        if(!out[i])t.pb(i);
    }
    re(i,si(s))d[s[i]][s[i]]=1,q.push(s[i]);
    for(int x,y;si(q);){
        x=q.front();q.pop();
        re(i,si(g[x])){
            y=g[x][i];
            if(!--in[y])q.push(y);
            re(j,si(s))(d[s[j]][y]+=d[s[j]][x])%=p;
        }
    }
    int ans=1,N=si(s);
    re(i,N)re(j,N)f[i][j]=d[s[i]][t[j]];
    re(i,N){
        For(j,i+1,N)while(f[j][i]){
            ll l=f[i][i]/f[j][i];
            For(k,i,N)(f[i][k]-=l*f[j][k])%p;
            For(k,i,N)swap(f[i][k],f[j][k]);
            ans*=-1;
        }
        (ans*=f[i][i])%=p;if(ans<0)ans+=p;
    }cout<<(ans+p)%p<<endl;
    return 0;
}


#include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define X first
#define Y second
#define fill(A,B) memset(A,B,sizeof(A))
#define For(i,A,B) for(int i=(A);i<(int)(B);i++)
#define rep(i,A,B) for(int i=(A);i<=(B);i++)
#define dep(i,B,A) for(int i=(B);i>=(A);i--)
#define re(i,A) for(int i=0;i<(int)(A);i++)
#define de(i,A) for(int i=(A)-1;~i;i--)
#define inf (1LL<<62)
#define mn 777
#define P 1000000007
#define si(x) ((int)x.size())
#define MAX(A,B) A=max(A,B)
#define MIN(A,B) A=min(A,B)
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
inline ll pow(ll a,int b){ll tmp=1;for(;b;b>>=1){if(b&1)tmp=(ll)tmp*a%P;a=(ll)a*a%P;}return tmp;}
template<class T>inline void R(T &xx){xx=0;char ch=getchar();bool F=0;while((ch<'0'||ch>'9')&&ch!='-')ch=getchar();if(ch=='-')F=1,ch=getchar();while(ch>='0'&&ch<='9')xx=xx+xx+(xx<<3)+ch-48,ch=getchar();if(F)xx=-xx;}

queue<int>q;
int n,m,p,x,y;vector<int>s,t,g[mn];
int in[mn],out[mn];
ll d[mn][mn],f[mn][mn],ans=1;
int main(){
#ifndef ONLINE_JUDGE
    freopen("1.in","r",stdin);
    //freopen("2.out","w",stdout);
#endif
    R(n),R(m),R(p);
    re(i,m){
        R(x),R(y);
        g[x].pb(y);in[y]++;out[x]++;
    }
    rep(i,1,n){
        if(!in[i])s.pb(i);
        if(!out[i])t.pb(i);
    }int N=si(s);
    re(i,N)d[s[i]][s[i]]=1,q.push(s[i]);
    for(int x,y;si(q);){
        x=q.front();q.pop();
        re(i,si(g[x])){
            y=g[x][i];
            if(!--in[y])q.push(y);
            re(j,N)(d[s[j]][y]+=d[s[j]][x])%=p;
        }
    }
    re(i,N)re(j,N)f[i][j]=d[s[i]][t[j]];
    re(i,N){
        For(j,i+1,N)while(f[j][i]){
            ll l=f[i][i]/f[j][i];
            For(k,i,N)(f[i][k]-=l*f[j][k])%p;
            For(k,i,N)swap(f[i][k],f[j][k]);
            ans*=-1;
        }
        (ans*=f[i][i])%=p;if(ans<0)ans+=p;
    }cout<<(ans+p)%p<<endl;
    return 0;
}


#include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define X first
#define Y second
#define fill(A,B) memset(A,B,sizeof(A))
#define For(i,A,B) for(int i=(A);i<(int)(B);i++)
#define rep(i,A,B) for(int i=(A);i<=(B);i++)
#define dep(i,B,A) for(int i=(B);i>=(A);i--)
#define re(i,A) for(int i=0;i<(int)(A);i++)
#define de(i,A) for(int i=(A)-1;~i;i--)
#define inf (1LL<<62)
#define mn 2333
#define P 1000000007
#define si(x) ((int)x.size())
#define MAX(A,B) A=max(A,B)
#define MIN(A,B) A=min(A,B)
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
inline ll pow(ll a,int b){ll tmp=1;for(;b;b>>=1){if(b&1)tmp=(ll)tmp*a%P;a=(ll)a*a%P;}return tmp;}
template<class T>inline void R(T &xx){xx=0;char ch=getchar();bool F=0;while((ch<'0'||ch>'9')&&ch!='-')ch=getchar();if(ch=='-')F=1,ch=getchar();while(ch>='0'&&ch<='9')xx=xx+xx+(xx<<3)+ch-48,ch=getchar();if(F)xx=-xx;}

queue<int>q;
int n,m,p,x,y;vector<int>s,t,g[mn];
int in[mn],out[mn];
ll d[mn][mn],f[mn][mn],ans;
int main(){
#ifndef ONLINE_JUDGE
    freopen("1.in","r",stdin);
    //freopen("2.out","w",stdout);
#endif
    R(n),R(m),R(p);
    rep(i,1,m){
        R(x),R(y);
        g[x].pb(y);in[y]++;out[x]++;
    }
    rep(i,1,n){
        if(!in[i])s.pb(i);
        if(!out[i])t.pb(i);
    }
    re(i,si(s))d[s[i]][s[i]]=1,q.push(s[i]);
    for(int x,y;si(q);){
        x=q.front();q.pop();
        re(i,si(g[x])){
            y=g[x][i];
            if(!--in[y])q.push(y);
            re(j,si(s))(d[s[j]][y]+=d[s[j]][x])%=p;
        }
    }
    int ans=1,N=si(s);
    re(i,N)re(j,N)f[i][j]=d[s[i]][t[j]];
    re(i,N){
        For(j,i+1,N)while(f[j][i]){
            ll l=f[i][i]/f[j][i];
            For(k,i,N)(f[i][k]-=l*f[j][k])%p;
            For(k,i,N)swap(f[i][k],f[j][k]);
            ans*=-1;
        }
        (ans*=f[i][i])%=p;
    }cout<<(ans+p)%p<<endl;
    return 0;
}


#include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define X first
#define Y second
#define fill(A,B) memset(A,B,sizeof(A))
#define For(i,A,B) for(int i=(A);i<(int)(B);i++)
#define rep(i,A,B) for(int i=(A);i<=(B);i++)
#define dep(i,B,A) for(int i=(B);i>=(A);i--)
#define re(i,A) for(int i=0;i<(int)(A);i++)
#define de(i,A) for(int i=(A)-1;~i;i--)
#define inf (1LL<<62)
#define mn 2333
#define P 1000000007
#define si(x) ((int)x.size())
#define MAX(A,B) A=max(A,B)
#define MIN(A,B) A=min(A,B)
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
inline ll pow(ll a,int b){ll tmp=1;for(;b;b>>=1){if(b&1)tmp=(ll)tmp*a%P;a=(ll)a*a%P;}return tmp;}
template<class T>inline void R(T &xx){xx=0;char ch=getchar();bool F=0;while((ch<'0'||ch>'9')&&ch!='-')ch=getchar();if(ch=='-')F=1,ch=getchar();while(ch>='0'&&ch<='9')xx=xx+xx+(xx<<3)+ch-48,ch=getchar();if(F)xx=-xx;}

queue<int>q;
int n,m,p,x,y;vector<int>s,t,g[mn];
int in[mn],out[mn];
ll d[mn][mn],f[mn][mn],ans;
int main(){
#ifndef ONLINE_JUDGE
    freopen("1.in","r",stdin);
    //freopen("2.out","w",stdout);
#endif
    R(n),R(m),R(p);
    rep(i,1,m){
        R(x),R(y);
        g[x].pb(y);in[y]++;out[x]++;
    }
    rep(i,1,n){
        if(!in[i])s.pb(i);
        if(!out[i])t.pb(i);
    }
    re(i,si(s))d[s[i]][s[i]]=1,q.push(s[i]);
    for(int x,y;si(q);){
        x=q.front();q.pop();
        re(i,si(g[x])){
            y=g[x][i];
            if(!--in[y])q.push(y);
            re(j,si(s))(d[s[j]][y]+=d[s[j]][x])%=p;
        }
    }
    int ans=1,N=si(s);
    re(i,N)re(j,N)f[i][j]=d[s[i]][t[j]];
    re(i,N){
        For(j,i+1,N)while(f[j][i]){
            ll l=f[i][i]/f[j][i];
            For(k,i,N)(f[i][k]-=l*f[j][k])%p;
            swap(f[i],f[j]);
            ans*=-1;
        }
        (ans*=f[i][i])%=p;
    }cout<<(ans+p)%p<<endl;
    return 0;
}


#include<cstdio>
#include<cstring>
#include<algorithm>
#include<set>
#include<vector>
#include<map>
#include<queue>
#include<string>
#include<bitset>
#include<iomanip>
#include<iostream>
#include<cmath>
using namespace std;
#define rep(i,x,y) for(i=x;i<=y;i++)
#define _rep(i,x,y) for(i=x;i>=y;i--)
#define REP(i,x,y) for(int i=(x);i<=(y);i++)
#define _REP(i,x,y) for(int i=(x);i>=(y);i--)
#define CL(S,x) memset(S,x,sizeof(S))
#define CP(S1,S2) memcpy(S1,S2,sizeof(S2))
#define ALL(x,S) for(x=S.begin();x!=S.end();x++)
#define pb push_back
#define IN insert
#define ER erase
#define BE begin()
#define ED end()
#define LB lower_bound
#define UB upper_bound
#define mp make_pair
#define fi first
#define se second
#define upmin(x,y) x=min(x,y)
#define upmax(x,y) x=max(x,y)
#define COUT(S,x) cout<<fixed<<setprecision(x)<<S<<endl
template<class T> inline void read(T&x){bool fu=0;char c;for(c=getchar();c<=32;c=getchar());if(c=='-')fu=1,c=getchar();for(x=0;c>32;c=getchar())x=x*10+c-'0';if(fu)x=-x;};
template<class T> inline void read(T&x,T&y){read(x);read(y);}
template<class T> inline void read(T&x,T&y,T&z){read(x);read(y);read(z);}
inline char getc(){char c;for(c=getchar();c<=32;c=getchar());return c;}

typedef long long ll;
typedef long double ld;
typedef pair<int,int> pii;

int n,m,st,i,j,k,l,K,P,x,y;
int D0[610],D1[610],n0[610],n1[610];
int e[610][610];
ll a[610][610];

bool vis[610];ll f[610];

ll dfs(int i)
{
	if(i==st)return 1;
	if(vis[i])return f[i];vis[i]=1;
	ll ans=0;for(int j=1;j<=n;j++)ans=(ans+dfs(j)*e[j][i])%P;
	return f[i]=ans;
}
int main()
{
    //freopen("1.in","r",stdin);freopen("1.out","w",stdout);
	read(n,m,P);
	rep(i,1,m)read(x,y),e[x][y]++,D0[x]++,D1[y]++;
	rep(i,1,n)if(D0[i]==0)n0[i]=++n0[0];
	rep(i,1,n)if(D1[i]==0)n1[i]=++n1[0];
	K=n0[0];

	rep(i,1,n)if(n1[i])
	{
		CL(vis,0);CL(f,0);st=i;
		rep(j,1,n)if(n0[j])a[n1[i]][n0[j]]=dfs(j);
	}

	ll ans=1;
	rep(i,1,K)
	{
		rep(j,i,K)if(a[j][i]){if(j!=i)ans=-ans;rep(k,i,K)swap(a[j][k],a[i][k]);break;}
		if(a[i][i]==0)continue;
		rep(j,i+1,K)while(a[j][i])
		{
			ll res=a[j][i]/a[i][i];
			rep(k,i,K)a[j][k]=(a[j][k]-a[i][k]*res)%P;
			if(a[j][i]){ans=-ans;rep(k,i,K)swap(a[j][k],a[i][k]);}
		}
	}

	rep(i,1,K)ans=ans*a[i][i]%P;if(ans<0)ans+=P;
	cout<<ans<<endl;

    return 0;
}


#include<cstdio>
#include<cstring>
#include<algorithm>
#include<set>
#include<vector>
#include<map>
#include<queue>
#include<string>
#include<bitset>
#include<iomanip>
#include<iostream>
#include<cmath>
using namespace std;
#define rep(i,x,y) for(i=x;i<=y;i++)
#define _rep(i,x,y) for(i=x;i>=y;i--)
#define REP(i,x,y) for(int i=(x);i<=(y);i++)
#define _REP(i,x,y) for(int i=(x);i>=(y);i--)
#define CL(S,x) memset(S,x,sizeof(S))
#define CP(S1,S2) memcpy(S1,S2,sizeof(S2))
#define ALL(x,S) for(x=S.begin();x!=S.end();x++)
#define pb push_back
#define IN insert
#define ER erase
#define BE begin()
#define ED end()
#define LB lower_bound
#define UB upper_bound
#define mp make_pair
#define fi first
#define se second
#define upmin(x,y) x=min(x,y)
#define upmax(x,y) x=max(x,y)
#define COUT(S,x) cout<<fixed<<setprecision(x)<<S<<endl
template<class T> inline void read(T&x){bool fu=0;char c;for(c=getchar();c<=32;c=getchar());if(c=='-')fu=1,c=getchar();for(x=0;c>32;c=getchar())x=x*10+c-'0';if(fu)x=-x;};
template<class T> inline void read(T&x,T&y){read(x);read(y);}
template<class T> inline void read(T&x,T&y,T&z){read(x);read(y);read(z);}
inline char getc(){char c;for(c=getchar();c<=32;c=getchar());return c;}

typedef long long ll;
typedef long double ld;
typedef pair<int,int> pii;

int n,m,st,i,j,k,l,K,P,x,y;
int D0[610],D1[610],n0[610],n1[610];
int e[610][610];
ll a[610][610];

bool vis[610];ll f[610];

ll dfs(int i)
{
	if(i==st)return 1;
	if(vis[i])return f[i];vis[i]=1;
	ll ans=0;
	for(int j=1;j<=n;j++)if(e[j][i])
	ans=(ans+dfs(j)*e[j][i])%P;
	return f[i]=ans;
}
int main()
{
    //freopen("1.in","r",stdin);freopen("1.out","w",stdout);
	read(n,m,P);
	rep(i,1,m)read(x,y),e[x][y]++,D0[x]++,D1[y]++;
	rep(i,1,n)if(D0[i]==0)n0[i]=++n0[0];
	rep(i,1,n)if(D1[i]==0)n1[i]=++n1[0];
	K=n0[0];

	rep(i,1,n)if(n1[i])
	{
		CL(vis,0);CL(f,0);st=i;
		rep(j,1,n)if(n0[j])
		a[n1[i]][n0[j]]=dfs(j);
	}

	//rep(i,1,K)rep(j,1,K)printf("%I64d%s",a[i][j],j==K?"\n":" ");

	ll ans=1;
	rep(i,1,K)
	{
		rep(j,i,K)if(a[j][i]){if(j!=i)ans=-ans;rep(k,i,K)swap(a[j][k],a[i][k]);break;}
		if(a[i][i]==0)continue;
		rep(j,i+1,K)while(a[j][i])
		{
			ll res=a[j][i]/a[i][i];
			rep(k,i,K)a[j][k]=(a[j][k]-a[i][k]*res)%P;
			if(a[j][i]){ans=-ans;rep(k,i,K)swap(a[j][k],a[i][k]);}
		}
	}

	rep(i,1,K)ans=ans*a[i][i]%P;if(ans<0)ans+=P;
	cout<<ans<<endl;

    return 0;
}


#include<stdio.h>
#include<iostream>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
#include<vector>
using namespace std;
#define fr(i,n) for(int i=0;i<n;i++)
#define fo(i,n) for(int i=1;i<=n;i++)
#define fe(i,n) for(__typeof(n.begin()) i=n.begin();i!=n.end();i++)
typedef pair<int, int> ii;
typedef long long ll;
ll g[610][610], a[610][610];
int in[610], ot[610], e[610][610];
int n, m, p;
int q[610], b, f;
int s[610], t[610], sc, tc, tot;
bool st[610];
void inc(ll &x, ll y) {
	x = (x + y) % p;
}
int main() {
	scanf("%d%d%d", &n, &m, &p);
	fr(i,m)
	{
		int x, y;
		scanf("%d%d", &x, &y);
		in[y]++, ot[x]++;
		e[x][y]++;
	}
	fo(i,n)
	{
		if (!in[i])
			s[++sc] = i;
		if (!ot[i])
			t[++tc] = i;
		st[i] = !in[i] && !ot[i];
	}
	fo(i,n)
		if (!in[i])
			q[f++] = i, g[i][i] = 1;
	while (b < f) {
		int x = q[b++];
		fo(y,n)
			if (e[x][y]) {
				fo(i,sc)
					inc(g[s[i]][y], g[s[i]][x] * e[x][y] % p);
				in[y] -= e[x][y];
				if (!in[y])
					q[f++] = y;
			}
	}
	n = sc;
	fo(i,sc)
		fo(j,tc)
			a[i][j] = g[s[i]][t[j]];
	ll z = 1;
	fo(i,n)
	{
		for (int j = i + 1; j <= n; j++)
			while (a[j][i] != 0) {
				int d = a[i][i] / a[j][i];
				fo(k,n)
				{
					a[i][k] = (a[i][k] - a[j][k] * d) % p;
					swap(a[i][k], a[j][k]);
				}
				z = -z;
			}
		z = z * a[i][i] % p;
	}
	cout << (z + p) % p << endl;
	return 0;
}


#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <ctime>
//#include <cmath>
#include <vector>
#include <map>
using namespace std;
typedef long long LL;
typedef pair<int,int> pint;
typedef pair<LL,LL> pll;
#define fi first
#define se second
typedef map<int,int> mapint;
typedef vector<int> vint;
typedef vector<vint> vintp;
#define rep(i,j,k) for (int i = (j);i <= (k);i ++)
#define ran2 (rand() % 32000 * 32000 + rand() % 32000)
#define pb push_back
#define mp make_pair
#define mx 700

int m,n,j,k,l,i,o,p,__t,mod;
LL step[mx][mx],In[mx],Out[mx],Repre[mx],In_num,Out_num;
int L[mx * mx],op,ed,inque[mx];
LL Way[mx];

char ch;
void read(int &a){
	for (ch = getchar();(ch < '0' || ch > '9') && (ch != '-');ch = getchar());
	if (ch == '-') a = 0,__t = -1; else a = ch - '0',__t = 1;
	for (ch = getchar();ch >= '0' && ch <= '9';ch = getchar()) a = a * 10 + ch - '0';
	a *= __t;
}

struct matrix{
	LL M[mx][mx];

	void set(int x, int y, int a){
		M[x][y] = a;
	}

	void swap_line(int a, int b){
		rep(i, 1, In_num)
			swap(M[a][i], M[b][i]);
	}

	void solve(){
		LL ans = 1;
		rep(i, 1, In_num){
			bool find = 0;
			rep(j, i, In_num)
				if (M[j][i] != 0){
					find = 1;
					swap_line(i, j);
					if (i != j) ans *= -1;
					break;
				}
			rep(j, i + 1, In_num)
				if (M[j][i] != 0){
					for (; M[j][i] != 0; ){
						if (abs(M[j][i]) < abs(M[i][i]))
							swap_line(i, j), ans *= -1;
						LL dec = M[j][i] / M[i][i];
						rep(k, i, In_num)
							M[j][k] = (M[j][k] - M[i][k] * dec) % mod;
					}
				}
			ans = (ans * M[i][i]) % mod;
		}
		cout << (ans + mod) % mod << endl;
	}

} mat;

int main(){
	read(m), read(n), read(mod);
	rep(i, 1, n){
		read(j), read(k);
		step[j][k] ++;
		Out[j] ++;
		In[k] ++;
	}
	rep(i, 1, m)
		if (Out[i] == 0) Repre[i] = ++ Out_num;

	rep(i, 1, m)
		if (In[i] == 0){
			memset(Way, 0, sizeof Way);
			memset(inque, 0, sizeof inque);
			Way[i] = 1;
			inque[L[op = ed = 1] = i] = 1;
			++ In_num;
			for (int now = L[ed]; ed <= op; ed ++, now = L[ed])
				rep(def, 1, m)
					if (step[now][def] > 0)
						Way[def] = (Way[def] + step[now][def]) % mod;
			rep(j, 1, m)
				if (Repre[j] != 0)
					mat.set(In_num, Repre[j], Way[j]);
		}
	mat.solve();
}


#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <ctime>
//#include <cmath>
#include <vector>
#include <map>
using namespace std;
typedef long long LL;
typedef pair<int,int> pint;
typedef pair<LL,LL> pll;
#define fi first
#define se second
typedef map<int,int> mapint;
typedef vector<int> vint;
typedef vector<vint> vintp;
#define rep(i,j,k) for (int i = (j);i <= (k);i ++)
#define ran2 (rand() % 32000 * 32000 + rand() % 32000)
#define pb push_back
#define mp make_pair
#define mx 700

int m,n,j,k,l,i,o,p,__t,mod;
LL step[mx][mx],In[mx],Out[mx],Repre[mx],In_num,Out_num;
int L[mx * mx],op,ed,inque[mx],deg[mx];
LL Way[mx];

char ch;
void read(int &a){
	for (ch = getchar();(ch < '0' || ch > '9') && (ch != '-');ch = getchar());
	if (ch == '-') a = 0,__t = -1; else a = ch - '0',__t = 1;
	for (ch = getchar();ch >= '0' && ch <= '9';ch = getchar()) a = a * 10 + ch - '0';
	a *= __t;
}

struct matrix{
	LL M[mx][mx];

	void set(int x, int y, int a){
		M[x][y] = a;
	}

	void swap_line(int a, int b){
		rep(i, 1, In_num)
			swap(M[a][i], M[b][i]);
	}

	void solve(){
		LL ans = 1;
		rep(i, 1, In_num){
			bool find = 0;
			rep(j, i, In_num)
				if (M[j][i] != 0){
					find = 1;
					swap_line(i, j);
					if (i != j) ans *= -1;
					break;
				}
			rep(j, i + 1, In_num)
				if (M[j][i] != 0){
					for (; M[j][i] != 0; ){
						if (abs(M[j][i]) < abs(M[i][i]))
							swap_line(i, j), ans *= -1;
						LL dec = M[j][i] / M[i][i];
						rep(k, i, In_num)
							M[j][k] = (M[j][k] - M[i][k] * dec) % mod;
					}
				}
			ans = (ans * M[i][i]) % mod;
		}
		cout << (ans + mod) % mod << endl;
	}

} mat;

int main(){
	read(m), read(n), read(mod);
	rep(i, 1, n){
		read(j), read(k);
		step[j][k] ++;
		Out[j] ++;
		In[k] ++;
	}
	rep(i, 1, m)
		if (Out[i] == 0) Repre[i] = ++ Out_num;

	rep(i, 1, m)
		if (In[i] == 0){
			memset(Way, 0, sizeof Way);
			memset(inque, 0, sizeof inque);
			Way[i] = 1;
			inque[L[op = ed = 1] = i] = 1;
			++ In_num;
			n = 0;
			for (int now = L[ed]; ed <= op; ed ++, now = L[ed])
				rep(def, 1, m)
					if (step[now][def] > 0)
						if (!inque[def])
							inque[L[++ op] = def] = 1;
			for (int i = 1; i <= op; i ++){
				rep(j, 1, m)
					if (inque[j] && j != i && step[L[i]][j])
						deg[L[i]] ++;
				if (deg[L[i]] == 0) L[++ n] = L[i];
			}

			for (op = n, ed = 1; ed <= op; ed ++){
				int now = L[ed];
				rep(i, 1, m)
					if (inque[i] && deg[i] > 0 && step[i][now] > 0){
						deg[i] --;
						if (deg[i] == 0) L[++ op] = i;
					}
			}

			for (int i = op; i; i --)
				rep(j, 1, m)
					if (step[L[i]][j])
						Way[j] = (Way[j] + step[L[i]][j] * Way[L[i]]) % mod;

			rep(j, 1, m)
				if (Repre[j] != 0)
					mat.set(In_num, Repre[j], Way[j]);
		}
	mat.solve();
}


#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <ctime>
//#include <cmath>
#include <vector>
#include <map>
using namespace std;
typedef long long LL;
typedef pair<int,int> pint;
typedef pair<LL,LL> pll;
#define fi first
#define se second
typedef map<int,int> mapint;
typedef vector<int> vint;
typedef vector<vint> vintp;
#define rep(i,j,k) for (int i = (j);i <= (k);i ++)
#define ran2 (rand() % 32000 * 32000 + rand() % 32000)
#define pb push_back
#define mp make_pair
#define mx 700

int m,n,j,k,l,i,o,p,__t,mod;
LL step[mx][mx],In[mx],Out[mx],Repre[mx],In_num,Out_num;
int L[mx * mx],op,ed,inque[mx],deg[mx];
LL Way[mx];

char ch;
void read(int &a){
	for (ch = getchar();(ch < '0' || ch > '9') && (ch != '-');ch = getchar());
	if (ch == '-') a = 0,__t = -1; else a = ch - '0',__t = 1;
	for (ch = getchar();ch >= '0' && ch <= '9';ch = getchar()) a = a * 10 + ch - '0';
	a *= __t;
}

struct matrix{
	LL M[mx][mx];

	void set(int x, int y, int a){
		M[x][y] = a;
	}

	void swap_line(int a, int b){
		rep(i, 1, In_num)
			swap(M[a][i], M[b][i]);
	}

	void solve(){
		LL ans = 1;
		rep(i, 1, In_num){
			bool find = 0;
			rep(j, i, In_num)
				if (M[j][i] != 0){
					find = 1;
					swap_line(i, j);
					if (i != j) ans *= -1;
					break;
				}
			rep(j, i + 1, In_num)
				if (M[j][i] != 0){
					for (; M[j][i] != 0; ){
						if (abs(M[j][i]) < abs(M[i][i]))
							swap_line(i, j), ans *= -1;
						LL dec = M[j][i] / M[i][i];
						rep(k, i, In_num)
							M[j][k] = (M[j][k] - M[i][k] * dec) % mod;
					}
				}
			ans = (ans * M[i][i]) % mod;
		}
		cout << (ans + mod) % mod << endl;
	}

} mat;

int main(){
	read(m), read(n), read(mod);
	rep(i, 1, n){
		read(j), read(k);
		step[j][k] ++;
		Out[j] ++;
		In[k] ++;
	}
	rep(i, 1, m)
		if (Out[i] == 0) Repre[i] = ++ In_num;

	rep(i, 1, m)
		if (In[i] == 0){
			memset(Way, 0, sizeof Way);
			memset(inque, 0, sizeof inque);
			Way[i] = 1;
			inque[L[op = ed = 1] = i] = 1;
			++ Out_num;
			n = 0;
			for (int now = L[ed]; ed <= op; ed ++, now = L[ed])
				rep(def, 1, m)
					if (step[now][def] > 0)
						if (!inque[def])
							inque[L[++ op] = def] = 1;
			for (int i = 1; i <= op; i ++){
				rep(j, 1, m)
					if (inque[j] && j != i && step[L[i]][j])
						deg[L[i]] ++;
				if (deg[L[i]] == 0) L[++ n] = L[i];
			}

			for (op = n, ed = 1; ed <= op; ed ++){
				int now = L[ed];
				rep(i, 1, m)
					if (inque[i] && deg[i] > 0 && step[i][now] > 0){
						deg[i] --;
						if (deg[i] == 0)
							L[++ op] = i;
					}
			}

			for (int i = op; i; i --)
				rep(j, 1, m)
					if (step[L[i]][j])
						Way[j] = (Way[j] + step[L[i]][j] * Way[L[i]]) % mod;

			rep(j, 1, m)
				if (Repre[j] != 0)
					mat.set(Out_num, Repre[j], Way[j]);
		}
	mat.solve();
}


#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <ctime>
//#include <cmath>
#include <vector>
#include <map>
using namespace std;
typedef long long LL;
typedef pair<int,int> pint;
typedef pair<LL,LL> pll;
#define fi first
#define se second
typedef map<int,int> mapint;
typedef vector<int> vint;
typedef vector<vint> vintp;
#define rep(i,j,k) for (int i = (j);i <= (k);i ++)
#define ran2 (rand() % 32000 * 32000 + rand() % 32000)
#define pb push_back
#define mp make_pair
#define mx 700

int m,n,j,k,l,i,o,p,__t,mod;
LL step[mx][mx],In[mx],Out[mx],Repre[mx],In_num,Out_num;
int L[mx * mx],op,ed,inque[mx],deg[mx];
LL Way[mx];

char ch;
void read(int &a){
	for (ch = getchar();(ch < '0' || ch > '9') && (ch != '-');ch = getchar());
	if (ch == '-') a = 0,__t = -1; else a = ch - '0',__t = 1;
	for (ch = getchar();ch >= '0' && ch <= '9';ch = getchar()) a = a * 10 + ch - '0';
	a *= __t;
}

struct matrix{
	LL M[mx][mx];

	void set(int x, int y, int a){
		M[x][y] = a;
	}

	void swap_line(int a, int b){
		rep(i, 1, In_num)
			swap(M[a][i], M[b][i]);
	}

	void solve(){
		LL ans = 1;
		rep(i, 1, In_num){
			bool find = 0;
			rep(j, i, In_num)
				if (M[j][i] != 0){
					find = 1;
					swap_line(i, j);
					if (i != j) ans *= -1;
					break;
				}
			rep(j, i + 1, In_num)
				if (M[j][i] != 0){
					for (; M[j][i] != 0; ){
						if (abs(M[j][i]) < abs(M[i][i]))
							swap_line(i, j), ans *= -1;
						LL dec = M[j][i] / M[i][i];
						rep(k, i, In_num)
							M[j][k] = (M[j][k] - M[i][k] * dec) % mod;
					}
				}
			ans = (ans * M[i][i]) % mod;
		}
		cout << (ans + mod) % mod << endl;
	}

} mat;

int main(){
	read(m), read(n), read(mod);
	rep(i, 1, n){
		read(j), read(k);
		step[j][k] ++;
		Out[j] ++;
		In[k] ++;
	}
	rep(i, 1, m)
		if (Out[i] == 0) Repre[i] = ++ In_num;

	rep(i, 1, m)
		if (In[i] == 0){
			memset(Way, 0, sizeof Way);
			memset(inque, 0, sizeof inque);
			Way[i] = 1;
			inque[L[op = ed = 1] = i] = 1;
			++ Out_num;
			n = 0;
			for (int now = L[ed]; ed <= op; ed ++, now = L[ed])
				rep(def, 1, m)
					if (step[now][def] > 0)
						if (!inque[def])
							inque[L[++ op] = def] = 1;
			for (int i = 1; i <= op; i ++){
				rep(j, 1, m)
					if (inque[j] && j != L[i] && step[L[i]][j])
						deg[L[i]] ++;
				if (deg[L[i]] == 0) L[++ n] = L[i];
			}

			for (op = n, ed = 1; ed <= op; ed ++){
				int now = L[ed];
				rep(i, 1, m)
					if (inque[i] && deg[i] > 0 && step[i][now] > 0){
						deg[i] --;
						if (deg[i] == 0)
							L[++ op] = i;
					}
			}

			for (int i = op; i; i --)
				rep(j, 1, m)
					if (step[L[i]][j])
						Way[j] = (Way[j] + step[L[i]][j] * Way[L[i]]) % mod;

			rep(j, 1, m)
				if (Repre[j] != 0)
					mat.set(Out_num, Repre[j], Way[j]);
		}
	mat.solve();
}


//while(true)rp++;
#include<algorithm>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<iomanip>
#include<map>
#include<queue>
#include<stack>
#include<string>
#include<set>
#include<utility>
#include<vector>
using namespace std;
#define FF first
#define SS second
#define PB push_back
#define MP make_pair
typedef long long ll;
const ll INF=1<<28;
const ll LINF=1ll<<61;
int n,m,p,d,din[611],dout[611];
ll dp[611][611],a[611][611];
vector<int>con[611],rev[611],s,t;
bool neg;
int dfs(int x,int y)
{
    if(x==y)return 1;
    if(dp[x][y]!=-1)return dp[x][y];
    dp[x][y]=0;
    for(int i=0;i<rev[y].size();i++)
    {
        dp[x][y]=(dp[x][y]+dfs(x,rev[y][i]))%p;
    }
    return dp[x][y];
}
ll kissme(ll x,ll k)
{
    int ans=1;
    while(k>0)
    {
        if(k&1)ans=ans*x%p;
        k=k/2;
        x=x*x%p;
    }
    return ans;
}
int cal()
{
    for(int i=0;i<d;i++)
    {
        int ok=-1;
        for(int j=i;j<d;j++)if(a[j][i]>0){ok=j;break;}
        if(ok==-1)return 0;
        if(ok!=i)
        {
            for(int j=0;j<d;j++)swap(a[i][j],a[ok][j]);
            neg^=1;
        }
        for(int j=i+1;j<d;j++)
        {
            ll coef=(p-a[j][i])*kissme(a[i][i],p-2)%p;
            for(int k=j;k<d;k++)a[j][k]=(a[j][k]+a[i][k]*coef)%p;
        }
    }
/*  cout<<"d="<<d<<endl;
    for(int i=0;i<d;i++)
    {
        for(int j=0;j<d;j++)
        {
            cout<<a[i][j]<<" ";
        }
        cout<<endl;
    }*/
    ll ans=(neg?p-1:1);
    for(int i=0;i<d;i++)ans=ans*a[i][i]%p;
    return ans;
}
int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>m>>p;int x,y;
    for(int i=1;i<=m;i++)
    {
        cin>>x>>y;
        con[x].PB(y);
        rev[y].PB(x);
        din[y]++;
        dout[x]++;
    }
    for(int i=1;i<=n;i++)
    {
        if(din[i]==0&&dout[i]>0)s.PB(i),d++;
        if(din[i]>0&&dout[i]==0)t.PB(i);
    }
    for(int i=1;i<=n;i++)for(int j=1;j<=n;j++)dp[i][j]=-1;
    for(int i=0;i<d;i++)for(int j=0;j<d;j++)a[i][j]=dfs(s[i],t[j]);
    ll ans=cal();
    bool neg=0;
    for(int i=1;i<=n;i++)if(din[i]+dout[i]==0)
    {
        int cnt1=0,cnt2=0;
        for(int j=0;j<d;j++)if(s[j]<i)cnt1++;
        for(int j=0;j<d;j++)if(t[j]<i)cnt2++;
        if(cnt1%2!=cnt2%2)neg^=1;
    }
    if(neg)ans=p-ans;
    cout<<ans<<endl;
    return 0;
}


//while(true)rp++;
#include<algorithm>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<iomanip>
#include<map>
#include<queue>
#include<stack>
#include<string>
#include<set>
#include<utility>
#include<vector>
using namespace std;
#define FF first
#define SS second
#define PB push_back
#define MP make_pair
typedef long long ll;
const ll INF=1<<28;
const ll LINF=1ll<<61;
int n,m,p,d,din[611],dout[611];
ll dp[611][611],a[611][611];
vector<int>con[611],rev[611],s,t;
ll dfs(int x,int y)
{
    if(x==y)return dp[x][y]=1;
    if(dp[x][y]!=-1)return dp[x][y];
    dp[x][y]=0;
    for(int i=0;i<rev[y].size();i++)
    {
        dp[x][y]=(dp[x][y]+dfs(x,rev[y][i]))%p;
    }
    return dp[x][y];
}
ll kissme(ll x,ll k)
{
    int ans=1;
    while(k>0)
    {
        if(k&1)ans=ans*x%p;
        k=k/2;
        x=x*x%p;
    }
    return ans;
}
ll cal()
{
    bool neg=0;
    for(int i=0;i<d;i++)
    {
        int ok=-1;
        for(int j=i;j<d;j++)if(a[j][i]!=0){ok=j;break;}
        if(ok==-1)return 0;
        if(ok!=i)
        {
            for(int j=0;j<d;j++)swap(a[i][j],a[ok][j]);
            neg^=1;
        }
        for(int j=i+1;j<d;j++)
        {
            ll coef=(p-a[j][i])*kissme(a[i][i],p-2)%p;
            for(int k=j;k<d;k++)a[j][k]=(a[j][k]+a[i][k]*coef)%p;
        }
    }
    ll ans=(neg?(p-1):1);
    for(int i=0;i<d;i++)ans=ans*a[i][i]%p;
    return ans;
}
int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>m>>p;int x,y;
    for(int i=1;i<=m;i++)
    {
        cin>>x>>y;
        con[x].PB(y);
        rev[y].PB(x);
        din[y]++;
        dout[x]++;
    }
    for(int i=1;i<=n;i++)
    {
        if(din[i]==0&&dout[i]>0)s.PB(i);
        if(din[i]>0&&dout[i]==0)t.PB(i);
    }d=s.size();
    for(int i=1;i<=n;i++)for(int j=1;j<=n;j++)dp[i][j]=-1;
    for(int i=0;i<d;i++)for(int j=0;j<d;j++)a[i][j]=dfs(s[i],t[j]);
    ll ans=cal();
    bool neg=0;
    for(int i=1;i<=n;i++)if(din[i]==0&&dout[i]==0)
    {
        int cnt1=0,cnt2=0;
        for(int j=0;j<d;j++)if(s[j]<i)cnt1++;
        for(int j=0;j<d;j++)if(t[j]<i)cnt2++;
        if(cnt1%2!=cnt2%2)neg^=1;
    }
    if(neg)ans=(p-ans)%p;
    cout<<ans<<endl;
    return 0;
}


//while(true)rp++;
#include<algorithm>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<iomanip>
#include<map>
#include<queue>
#include<stack>
#include<string>
#include<set>
#include<utility>
#include<vector>
using namespace std;
#define FF first
#define SS second
#define PB push_back
#define MP make_pair
typedef long long ll;
const ll INF=1<<28;
const ll LINF=1ll<<61;
int n,m,p,d,din[611],dout[611];
ll dp[611][611],a[611][611];
vector<int>con[611],rev[611],s,t;
ll dfs(int x,int y)
{
    if(x==y)return 1;
    if(dp[x][y]!=-1)return dp[x][y];
    dp[x][y]=0;
    for(int i=0;i<rev[y].size();i++)
    {
        dp[x][y]=(dp[x][y]+dfs(x,rev[y][i]))%p;
    }
    return dp[x][y];
}
ll kissme(ll x,ll k)
{
    int ans=1;
    while(k>0)
    {
        if(k&1)ans=ans*x%p;
        k=k/2;
        x=x*x%p;
    }
    return ans;
}
int cal()
{
    bool neg=0;
    for(int i=0;i<d;i++)
    {
        int ok=-1;
        for(int j=i;j<d;j++)if(a[j][i]>0){ok=j;break;}
        if(ok==-1)return 0;
        if(ok!=i)
        {
            for(int j=0;j<d;j++)swap(a[i][j],a[ok][j]);
            neg^=1;
        }
        for(int j=i+1;j<d;j++)
        {
            ll coef=(p-a[j][i])*kissme(a[i][i],p-2)%p;
            for(int k=j;k<d;k++)a[j][k]=(a[j][k]+a[i][k]*coef)%p;
        }
    }
    ll ans=(neg?p-1:1);
    for(int i=0;i<d;i++)ans=ans*a[i][i]%p;
    return ans;
}
int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>m>>p;int x,y;
    for(int i=1;i<=m;i++)
    {
        cin>>x>>y;
        con[x].PB(y);
        rev[y].PB(x);
        din[y]++;
        dout[x]++;
    }
    for(int i=1;i<=n;i++)
    {
        if(din[i]==0&&dout[i]>0)s.PB(i),d++;
        if(din[i]>0&&dout[i]==0)t.PB(i);
    }
    for(int i=1;i<=n;i++)for(int j=1;j<=n;j++)dp[i][j]=-1;
    for(int i=0;i<d;i++)for(int j=0;j<d;j++)a[i][j]=dfs(s[i],t[j]);
    ll ans=cal();
    bool neg=0;
    for(int i=1;i<=n;i++)if(din[i]==0&&dout[i]==0)
    {
        int cnt1=0,cnt2=0;
        for(int j=0;j<d;j++)if(s[j]<i)cnt1++;
        for(int j=0;j<d;j++)if(t[j]<i)cnt2++;
        if(cnt1%2!=cnt2%2)neg^=1;
    }
    if(neg)ans=(p-ans)%p;
    cout<<ans<<endl;
    return 0;
}


//while(true)rp++;
#include<algorithm>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<iomanip>
#include<map>
#include<queue>
#include<stack>
#include<string>
#include<set>
#include<utility>
#include<vector>
using namespace std;
#define FF first
#define SS second
#define PB push_back
#define MP make_pair
typedef long long ll;
const ll INF=1<<28;
const ll LINF=1ll<<61;
int n,m,p,d,din[611],dout[611];
ll dp[611][611],a[611][611];
vector<int>con[611],rev[611],s,t;
ll dfs(int x,int y)
{
    if(x==y)return dp[x][y]=1;
    if(dp[x][y]!=-1)return dp[x][y];
    dp[x][y]=0;
    for(int i=0;i<rev[y].size();i++)
    {
        dp[x][y]=(dp[x][y]+dfs(x,rev[y][i]))%p;
    }
    return dp[x][y];
}
ll kissme(ll x,ll k)
{
    int ans=1;
    while(k>0)
    {
        if(k&1)ans=ans*x%p;
        k=k/2;
        x=x*x%p;
    }
    return ans;
}
ll cal()
{
    bool neg=0;
    for(int i=0;i<d;i++)
    {
        int ok=-1;
        for(int j=i;j<d;j++)if(a[j][i]!=0){ok=j;break;}
        if(ok==-1)return 0;
        if(ok!=i)
        {
            for(int j=0;j<d;j++)swap(a[i][j],a[ok][j]);
            neg^=1;
        }
        for(int j=i+1;j<d;j++)
        {
            ll coef=(p-a[j][i])*kissme(a[i][i],p-2)%p;
            for(int k=i;k<d;k++)a[j][k]=(a[j][k]+a[i][k]*coef)%p;
        }
    }
    ll ans=(neg?(p-1):1);
    for(int i=0;i<d;i++)ans=ans*a[i][i]%p;
    return ans;
}
int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>m>>p;int x,y;
    for(int i=1;i<=m;i++)
    {
        cin>>x>>y;
        con[x].PB(y);
        rev[y].PB(x);
        din[y]++;
        dout[x]++;
    }
    for(int i=1;i<=n;i++)
    {
        if(din[i]==0&&dout[i]>0)s.PB(i);
        if(din[i]>0&&dout[i]==0)t.PB(i);
    }d=s.size();
    for(int i=1;i<=n;i++)for(int j=1;j<=n;j++)dp[i][j]=-1;
    for(int i=0;i<d;i++)for(int j=0;j<d;j++)a[i][j]=dfs(s[i],t[j]);
    ll ans=cal();
    bool neg=0;
    for(int i=1;i<=n;i++)if(din[i]==0&&dout[i]==0)
    {
        int cnt1=0,cnt2=0;
        for(int j=0;j<d;j++)if(s[j]<i)cnt1++;
        for(int j=0;j<d;j++)if(t[j]<i)cnt2++;
        if(cnt1%2!=cnt2%2)neg^=1;
    }
    if(neg)ans=(p-ans)%p;
    cout<<ans<<endl;
    return 0;
}


//while(true)rp++;
#include<algorithm>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<iomanip>
#include<map>
#include<queue>
#include<stack>
#include<string>
#include<set>
#include<utility>
#include<vector>
using namespace std;
#define FF first
#define SS second
#define PB push_back
#define MP make_pair
typedef long long ll;
const ll INF=1<<28;
const ll LINF=1ll<<61;
int n,m,p,d,din[611],dout[611];
ll dp[611][611],a[611][611];
vector<int>con[611],rev[611],s,t;
bool neg;
ll dfs(int x,int y)
{
    if(x==y)return 1;
    if(dp[x][y]!=-1)return dp[x][y];
    dp[x][y]=0;
    for(int i=0;i<rev[y].size();i++)
    {
        dp[x][y]=(dp[x][y]+dfs(x,rev[y][i]))%p;
    }
    return dp[x][y];
}
ll kissme(ll x,ll k)
{
    int ans=1;
    while(k>0)
    {
        if(k&1)ans=ans*x%p;
        k=k/2;
        x=x*x%p;
    }
    return ans;
}
int cal()
{
    for(int i=0;i<d;i++)
    {
        int ok=-1;
        for(int j=i;j<d;j++)if(a[j][i]>0){ok=j;break;}
        if(ok==-1)return 0;
        if(ok!=i)
        {
            for(int j=0;j<d;j++)swap(a[i][j],a[ok][j]);
            neg^=1;
        }
        for(int j=i+1;j<d;j++)
        {
            ll coef=(p-a[j][i])*kissme(a[i][i],p-2)%p;
            for(int k=j;k<d;k++)a[j][k]=(a[j][k]+a[i][k]*coef)%p;
        }
    }
    ll ans=(neg?p-1:1);
    for(int i=0;i<d;i++)ans=ans*a[i][i]%p;
    return ans;
}
int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>m>>p;int x,y;
    for(int i=1;i<=m;i++)
    {
        cin>>x>>y;
        con[x].PB(y);
        rev[y].PB(x);
        din[y]++;
        dout[x]++;
    }
    for(int i=1;i<=n;i++)
    {
        if(din[i]==0&&dout[i]>0)s.PB(i),d++;
        if(din[i]>0&&dout[i]==0)t.PB(i);
    }
    for(int i=1;i<=n;i++)for(int j=1;j<=n;j++)dp[i][j]=-1;
    for(int i=0;i<d;i++)for(int j=0;j<d;j++)a[i][j]=dfs(s[i],t[j]);
    ll ans=cal();
    bool neg=0;
    for(int i=1;i<=n;i++)if(din[i]+dout[i]==0)
    {
        int cnt1=0,cnt2=0;
        for(int j=0;j<d;j++)if(s[j]<i)cnt1++;
        for(int j=0;j<d;j++)if(t[j]<i)cnt2++;
        if(cnt1%2!=cnt2%2)neg^=1;
    }
    if(neg)ans=(p-ans)%p;
    cout<<ans<<endl;
    return 0;
}


#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <cassert>
#include <initializer_list>
#include <unordered_map>
#include <unordered_set>

using namespace std;

#ifndef ONLINE_JUDGE
#define DEBUG
#endif

#define oo 0x3F3F3F3F
#ifdef DEBUG
#define cvar(x) cerr << "<" << #x << ": " << x << ">"
#define evar(x) cvar (x) << endl
template<class T> void DISP (const char *s, T x, int n) {cerr << "[" << s << ": "; for (int i = 0; i < n; ++i) cerr << x[i] << " "; cerr << "]" << endl;}
#define disp(x,n) DISP (#x " to " #n, x, n)
#else
#define cvar(...) ({})
#define evar(...) ({})
#define disp(...) ({})
#endif
#define MKP make_pair
#define Px first
#define Py second
#define PB push_back
#define SZ(x) (int)((x).size ())
#define ALL(x) (x).begin (), (x).end ()

typedef unsigned int uint;
typedef long long int64;
typedef unsigned long long uint64;
typedef long double real;
typedef vector<int> VI;
typedef map<int, int> MII;
typedef unordered_map<int, int> UMII;
typedef unordered_set<int> USI;
typedef set<int> SI;
typedef pair<int, int> PII;

int64 fpm (int64 b, int64 e, int64 m) { int64 t = 1; for (; e; e >>= 1, b = b * b % m) e & 1 ? t = t * b % m : 0; return t; }
template<class T> inline bool chkmin (T &a, T b) {return a > b ? a = b, true : false;}
template<class T> inline bool chkmax (T &a, T b) {return a < b ? a = b, true : false;}
template<class T> inline T sqr (T x) {return x * x;}

template<class edge> struct Graph
{
  vector<vector<edge> > adj;
  Graph (int n) {adj.clear (); adj.resize (n + 5);}
  Graph () {adj.clear (); }
  void resize (int n) {adj.resize (n + 5); }
  void add (int s, edge e){adj[s].push_back (e);}
  void del (int s, edge e) {adj[s].erase (find (iter (adj[s]), e)); }
  int deg (int v) {return adj[v].size (); }
  vector<edge>& operator [](int t) {return adj[t];}
};

const int maxn = 660;

Graph<int> G;
int ideg[maxn], odeg[maxn], f[maxn], rep[maxn];
int64 ways[maxn][maxn];
bool reach[maxn];

int main ()
{
#ifndef ONLINE_JUDGE
  freopen ("167E.in" , "r", stdin);
  freopen ("167E.out", "w", stdout);
#endif
  ios_base::sync_with_stdio (false);

  int n, m, mod;

  cin >> n >> m >> mod; G.resize (n);
  for (int i = 1, s, t; i <= m; ++i)
    cin >> s >> t, G.add (s, t), ++odeg[s], ++ideg[t];

  vector<int> S, T;
  for (int i = 1; i <= n; ++i)
    {
      if (!ideg[i])
        S.push_back (i);
      if (!odeg[i])
        T.push_back (i);
    }

  for (int v = 0; v < SZ (S); ++v)
    {
      queue<int> Q; Q.push (S[v]);
      memset (reach, 0, sizeof (reach));

      for (int u; !Q.empty (); Q.pop ())
        for (auto &x : G[u = Q.front ()])
          if (!reach[x])
            reach[x] = true, Q.push (x);

      memset (ideg, 0, sizeof (ideg));
      for (int i = 1; i <= n; ++i)
        if (reach[i])
          for (auto &u : G[i])
            ++ideg[u];

      Q.push (S[v]);
      memset (f, 0, sizeof (f)), f[S[v]] = 1;
      for (int u; !Q.empty (); Q.pop ())
        for (auto &x : G[u = Q.front ()])
          if (reach[x])
            {
              (f[x] += f[u]) %= mod;
              if (--ideg[x] == 0) Q.push (x);
            }

      for (int u = 0; u < SZ (T); ++u)
        ways[u][v] = f[T[u]];
    }

  // now, we're to perform Gaussian Elimination
  // the answer is the determination of the matrix `ways'
  int K = SZ (S); int64 ans = 1;
  for (int i = 0; i < K; ++i)
    rep[i] = i;

  for (int i = 0, j, k; i < K; ++i)
    {
      for (j = i; j < K; ++j)
        if (ways[j][i] != 0)
          break;
      for (k = 0; k < K; ++k)
        swap (ways[i][k], ways[j][k]);
      ans = ans * ways[i][i] % mod;
      swap (rep[i], rep[j]);

      int64 inv = fpm (ways[i][i], mod - 2, mod);
      for (j = i; j < K; ++j)
        ways[i][j] = ways[i][j] * inv % mod;
      for (j = K - 1; j > i; --j)
        for (k = K - 1; k > i; --k)
          ways[j][k] = (ways[j][k] + mod - ways[j][i] * ways[i][k] % mod) % mod;
    }
  for (int i = 0; i < K; ++i)
    for (int j = i + 1; j < K; ++j)
      if (rep[i] > rep[j])
        ans = (mod - ans) % mod;

  cout << ans << endl;
  return 0;
}


#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <cassert>
#include <initializer_list>
#include <unordered_map>
#include <unordered_set>

using namespace std;

#ifndef ONLINE_JUDGE
#define DEBUG
#endif

#define oo 0x3F3F3F3F
#ifdef DEBUG
#define cvar(x) cerr << "<" << #x << ": " << x << ">"
#define evar(x) cvar (x) << endl
template<class T> void DISP (const char *s, T x, int n) {cerr << "[" << s << ": "; for (int i = 0; i < n; ++i) cerr << x[i] << " "; cerr << "]" << endl;}
#define disp(x,n) DISP (#x " to " #n, x, n)
#else
#define cvar(...) ({})
#define evar(...) ({})
#define disp(...) ({})
#endif
#define MKP make_pair
#define Px first
#define Py second
#define PB push_back
#define SZ(x) (int)((x).size ())
#define ALL(x) (x).begin (), (x).end ()

typedef unsigned int uint;
typedef long long int64;
typedef unsigned long long uint64;
typedef long double real;
typedef vector<int> VI;
typedef map<int, int> MII;
typedef unordered_map<int, int> UMII;
typedef unordered_set<int> USI;
typedef set<int> SI;
typedef pair<int, int> PII;

int64 fpm (int64 b, int64 e, int64 m) { int64 t = 1; for (; e; e >>= 1, b = b * b % m) e & 1 ? t = t * b % m : 0; return t; }
template<class T> inline bool chkmin (T &a, T b) {return a > b ? a = b, true : false;}
template<class T> inline bool chkmax (T &a, T b) {return a < b ? a = b, true : false;}
template<class T> inline T sqr (T x) {return x * x;}

template<class edge> struct Graph
{
  vector<vector<edge> > adj;
  Graph (int n) {adj.clear (); adj.resize (n + 5);}
  Graph () {adj.clear (); }
  void resize (int n) {adj.resize (n + 5); }
  void add (int s, edge e){adj[s].push_back (e);}
  void del (int s, edge e) {adj[s].erase (find (iter (adj[s]), e)); }
  int deg (int v) {return adj[v].size (); }
  vector<edge>& operator [](int t) {return adj[t];}
};

const int maxn = 660;

Graph<int> G;
int ideg[maxn], odeg[maxn], f[maxn], rep[maxn];
int64 ways[maxn][maxn];
bool reach[maxn];

int main ()
{
#ifndef ONLINE_JUDGE
  freopen ("167E.in" , "r", stdin);
  freopen ("167E.out", "w", stdout);
#endif
  ios_base::sync_with_stdio (false);

  int n, m, mod;

  cin >> n >> m >> mod; G.resize (n);
  for (int i = 1, s, t; i <= m; ++i)
    cin >> s >> t, G.add (s, t), ++odeg[s], ++ideg[t];

  vector<int> S, T;
  for (int i = 1; i <= n; ++i)
    {
      if (!ideg[i])
        S.push_back (i);
      if (!odeg[i])
        T.push_back (i);
    }

  for (int v = 0; v < SZ (S); ++v)
    {
      memset (reach, 0, sizeof (reach));
      queue<int> Q; Q.push (S[v]), reach[S[v]] = 1;

      for (int u; !Q.empty (); Q.pop ())
        for (auto &x : G[u = Q.front ()])
          if (!reach[x])
            reach[x] = true, Q.push (x);

      memset (ideg, 0, sizeof (ideg));
      for (int i = 1; i <= n; ++i)
        if (reach[i])
          for (auto &u : G[i])
            ++ideg[u];

      Q.push (S[v]);
      memset (f, 0, sizeof (f)), f[S[v]] = 1;
      for (int u; !Q.empty (); Q.pop ())
        for (auto &x : G[u = Q.front ()])
          if (reach[x])
            {
              (f[x] += f[u]) %= mod;
              if (--ideg[x] == 0) Q.push (x);
            }

      for (int u = 0; u < SZ (T); ++u)
        ways[u][v] = f[T[u]];
    }

  // now, we're to perform Gaussian Elimination
  // the answer is the determination of the matrix `ways'
  int K = SZ (S); int64 ans = 1;
  for (int i = 0; i < K; ++i)
    rep[i] = i;

  // for (int i = 0; i < K; ++i)
  //   {
  //     for (int j = 0; j < K; ++j)
  //       cerr << ways[i][j] << " ";
  //     cerr << endl;
  //   }

  for (int i = 0, j, k; i < K; ++i)
    {
      for (j = i; j < K; ++j)
        if (ways[j][i] != 0)
          break;
      for (k = 0; k < K; ++k)
        swap (ways[i][k], ways[j][k]);
      ans = ans * ways[i][i] % mod;
      swap (rep[i], rep[j]);

      int64 inv = fpm (ways[i][i], mod - 2, mod);
      for (j = i; j < K; ++j)
        ways[i][j] = ways[i][j] * inv % mod;
      for (j = K - 1; j > i; --j)
        for (k = K - 1; k > i; --k)
          ways[j][k] = (ways[j][k] + mod - ways[j][i] * ways[i][k] % mod) % mod;
    }
  for (int i = 0; i < K; ++i)
    for (int j = i + 1; j < K; ++j)
      if (rep[i] > rep[j])
        ans = (mod - ans) % mod;

  cout << ans << endl;
  return 0;
}


// Determinant
// 行列式（ぎょうれつしき）

#include<cstdio>
#include<algorithm>

void Get(long long &T)
{
	char C;bool F=0;
	for(;C=getchar(),C<'0'||C>'9';)if(C=='-')F=1;
	for(T=C-'0';C=getchar(),C>='0'&&C<='9';T=T*10+C-'0');
	F&&(T=-T);
}

void Get(int &T)
{
	char C;bool F=0;
	for(;C=getchar(),C<'0'||C>'9';)if(C=='-')F=1;
	for(T=C-'0';C=getchar(),C>='0'&&C<='9';T=T*10+C-'0');
	F&&(T=-T);
}

struct E
{
	int V,Next;
}Edge[100005];
int EdgeTop;
int Head[605];

void Add(int U,int V)
{
	Edge[++EdgeTop]=(E){V,Head[U]};
	Head[U]=EdgeTop;
}

int N,M;
long long P;

int Out[605];
int In[605];

void Init()
{
	Get(N);Get(M);Get(P);
	for(int i=1,U,V;i<=M;i++)
	{
		Get(U);Get(V);
		Out[U]++;
		In[V]++;
		Add(U,V);
	}
}

bool S[605];
bool T[605];

int Q[605];
int L,R;

long long G[605][605];

int K;
int IDS[605];
int IDT[605];

long long A[305][305];

long long Pow(long long X,long long Y)
{
	long long Ans=1;
	for(;Y;Y>>=1)
	{
		if(Y&1) (Ans*=X)%=P;
		(X*=X)%=P;
	}
	return Ans;
}

long long Det(int N)
{
	long long Ans=1;

	for(int i=1;i<=N;i++)
	{
		if(A[i][i]==0)
		{
			int Choose=0;
			for(int j=i+1;j<=N;j++)
				if(A[j][i]!=0)
				{
					Choose=j;
					break;
				}

			if(Choose==0) return 0;

			for(int k=i;k<=N;k++)
				std::swap(A[i][k],A[Choose][k]);

			(Ans=-Ans)%=P;
			if(Ans<0) Ans+=P;
		}

		long long Inv=Pow(A[i][i],P-2);
		(Ans*=A[i][i])%=P;
		for(int k=i;k<=N;k++)
			(A[i][k]*=Inv)%=P;

		for(int j=i+1;j<=N;j++)
		{
			long long K=A[j][i];
			for(int k=i;k<=N;k++)
			{
				(A[j][k]-=A[i][k]*K)%=P;
				if(A[j][k]<0) A[j][k]+=P;
			}
		}
	}
	return Ans;
}

long long Ans;

void Work()
{
	L=1;
	for(int i=1,k=0;i<=N;i++)
	{
		if(In[i]==0)
		{
			S[i]=1;
			Q[++R]=i;
			In[i]=-1;
			K++;
			IDS[i]=K;
			G[K][i]=1;
		}
		if(Out[i]==0)
		{
			T[i]=1;
			k++;
			IDT[i]=k;
		}
	}

	for(;L<=R;L++)
	{
		for(int i=Head[Q[L]];i;i=Edge[i].Next)
		{
			In[Edge[i].V]--;
			if(In[Edge[i].V]==0)
			{
				Q[++R]=Edge[i].V;
				In[Edge[i].V]=-1;
			}
		}
	}

	for(int k=1,i;k<=N;k++)
	{
		i=Q[k];

		for(int j=Head[i];j;j=Edge[j].Next)
		{
			int V=Edge[j].V;
			for(int p=1;p<=K;p++)
			{
				(G[p][V]+=G[p][i])%=P;
			}

		}
	}

	for(int i=1;i<=N;i++)
		for(int j=1;j<=N;j++)
			if(S[i]==1&&T[j]==1)
			{
				A[IDS[i]][IDT[j]]=G[IDS[i]][j];
			}

	Ans=Det(K);
}

void Debug()
{
	P=99999989;

	A[1][1]=3;A[1][2]=8;
	A[2][1]=1;A[2][2]=4;

	long long Ans=Det(2);
	printf("%I64d\n",Ans);
}

void Output()
{

	printf("%I64d\n",Ans);
}

int main()
{
	Init();
	Work();
	Output();
	return 0;
}


// Determinant
// 行列式（ぎょうれつしき）

#include<cstdio>
#include<algorithm>

void Get(long long &T)
{
	char C;bool F=0;
	for(;C=getchar(),C<'0'||C>'9';)if(C=='-')F=1;
	for(T=C-'0';C=getchar(),C>='0'&&C<='9';T=T*10+C-'0');
	F&&(T=-T);
}

void Get(int &T)
{
	char C;bool F=0;
	for(;C=getchar(),C<'0'||C>'9';)if(C=='-')F=1;
	for(T=C-'0';C=getchar(),C>='0'&&C<='9';T=T*10+C-'0');
	F&&(T=-T);
}

struct E
{
	int V,Next;
}Edge[100005];
int EdgeTop;
int Head[605];

void Add(int U,int V)
{
	Edge[++EdgeTop]=(E){V,Head[U]};
	Head[U]=EdgeTop;
}

int N,M;
long long P;

int Out[605];
int In[605];

void Init()
{
	Get(N);Get(M);Get(P);
	for(int i=1,U,V;i<=M;i++)
	{
		Get(U);Get(V);
		Out[U]++;
		In[V]++;
		Add(U,V);
	}
}

bool S[605];
bool T[605];

int Q[605];
int L,R;

long long G[605][605];

int K;
int IDS[605];
int IDT[605];

long long A[305][305];

long long Pow(long long X,long long Y)
{
	long long Ans=1;
	for(;Y;Y>>=1)
	{
		if(Y&1) (Ans*=X)%=P;
		(X*=X)%=P;
	}
	return Ans;
}

long long Det(int N)
{
	long long Ans=1;

	for(int i=1;i<=N;i++)
	{
		if(A[i][i]==0)
		{
			int Choose=0;
			for(int j=i+1;j<=N;j++)
				if(A[j][i]!=0)
				{
					Choose=j;
					break;
				}

			if(Choose==0) return 0;

			for(int k=i;k<=N;k++)
				std::swap(A[i][k],A[Choose][k]);

			(Ans=-Ans)%=P;
			if(Ans<0) Ans+=P;
		}

		long long Inv=Pow(A[i][i],P-2);
		(Ans*=A[i][i])%=P;
		for(int k=i;k<=N;k++)
			(A[i][k]*=Inv)%=P;

		for(int j=i+1;j<=N;j++)
		{
			long long K=A[j][i];
			for(int k=i;k<=N;k++)
			{
				(A[j][k]-=A[i][k]*K)%=P;
				if(A[j][k]<0) A[j][k]+=P;
			}
		}
	}
	return Ans;
}

long long Ans;

void Work()
{
	bool Neg=0;

	L=1;
	for(int i=1,k=0;i<=N;i++)
	{
		if(In[i]==0&&Out[i]==0)
		{
			Neg^=((k+K)&1);
			continue;
		}
		if(In[i]==0)
		{
			S[i]=1;
			Q[++R]=i;
			In[i]=-1;
			K++;
			IDS[i]=K;
			G[K][i]=1;
		}
		if(Out[i]==0)
		{
			T[i]=1;
			k++;
			IDT[i]=k;
		}
	}

	for(;L<=R;L++)
	{
		for(int i=Head[Q[L]];i;i=Edge[i].Next)
		{
			In[Edge[i].V]--;
			if(In[Edge[i].V]==0)
			{
				Q[++R]=Edge[i].V;
				In[Edge[i].V]=-1;
			}
		}
	}

	for(int k=1,i;k<=N;k++)
	{
		i=Q[k];

		for(int j=Head[i];j;j=Edge[j].Next)
		{
			int V=Edge[j].V;
			for(int p=1;p<=K;p++)
			{
				(G[p][V]+=G[p][i])%=P;
			}

		}
	}

	for(int i=1;i<=N;i++)
		for(int j=1;j<=N;j++)
			if(S[i]==1&&T[j]==1)
			{
				A[IDS[i]][IDT[j]]=G[IDS[i]][j];
			}

	Ans=Det(K);
	if(Neg)
	{
		(Ans=-Ans)%=P;
		if(Ans<0) Ans+=P;
	}
}

void Debug()
{
	P=99999989;

	A[1][1]=3;A[1][2]=8;
	A[2][1]=1;A[2][2]=4;

	long long Ans=Det(2);
	printf("%I64d\n",Ans);
}

void Output()
{

	printf("%I64d\n",Ans);
}

int main()
{
	Init();
	Work();
	Output();
	return 0;
}


// Determinant
// 行列式（ぎょうれつしき）

#include<cstdio>
#include<algorithm>

void Get(long long &T)
{
	char C;bool F=0;
	for(;C=getchar(),C<'0'||C>'9';)if(C=='-')F=1;
	for(T=C-'0';C=getchar(),C>='0'&&C<='9';T=T*10+C-'0');
	F&&(T=-T);
}

void Get(int &T)
{
	char C;bool F=0;
	for(;C=getchar(),C<'0'||C>'9';)if(C=='-')F=1;
	for(T=C-'0';C=getchar(),C>='0'&&C<='9';T=T*10+C-'0');
	F&&(T=-T);
}

struct E
{
	int V,Next;
}Edge[100005];
int EdgeTop;
int Head[605];

void Add(int U,int V)
{
	Edge[++EdgeTop]=(E){V,Head[U]};
	Head[U]=EdgeTop;
}

int N,M;
long long P;

int Out[605];
int In[605];

void Init()
{
	Get(N);Get(M);Get(P);
	for(int i=1,U,V;i<=M;i++)
	{
		Get(U);Get(V);
		Out[U]++;
		In[V]++;
		Add(U,V);
	}
}

bool S[605];
bool T[605];

int Q[605];
int L,R;

long long G[605][605];

int K;
int IDS[605];
int IDT[605];

long long A[305][305];

long long Pow(long long X,long long Y)
{
	long long Ans=1;
	for(;Y;Y>>=1)
	{
		if(Y&1) (Ans*=X)%=P;
		(X*=X)%=P;
	}
	return Ans;
}

long long Det(int N)
{
	long long Ans=1;

	for(int i=1;i<=N;i++)
	{
		if(A[i][i]==0)
		{
			int Choose=0;
			for(int j=i+1;j<=N;j++)
				if(A[j][i]!=0)
				{
					Choose=j;
					break;
				}

			if(Choose==0) return 0;

			for(int k=i;k<=N;k++)
				std::swap(A[i][k],A[Choose][k]);

			Ans=P-Ans;
		}

		long long Inv=Pow(A[i][i],P-2);
		(Ans*=A[i][i])%=P;
		for(int k=i;k<=N;k++)
			(A[i][k]*=Inv)%=P;

		for(int j=i+1;j<=N;j++)
		{
			long long K=A[j][i];
			for(int k=i;k<=N;k++)
			{
				(A[j][k]+=P-(A[i][k]*K)%P)%=P;
			}
		}
	}
	return Ans;
}

long long Ans;

void Work()
{
	L=1;
	for(int i=1,k=0;i<=N;i++)
	{
		if(In[i]==0)
		{
			S[i]=1;
			Q[++R]=i;
			In[i]=-1;
			K++;
			IDS[i]=K;
			G[K][i]=1;
		}
		if(Out[i]==0)
		{
			T[i]=1;
			k++;
			IDT[i]=k;
		}
	}

	for(;L<=R;L++)
	{
		for(int i=Head[Q[L]];i;i=Edge[i].Next)
		{
			In[Edge[i].V]--;
			if(In[Edge[i].V]==0)
			{
				Q[++R]=Edge[i].V;
				In[Edge[i].V]=-1;
			}
		}
	}

	for(int k=1,i;k<=N;k++)
	{
		i=Q[k];

		for(int j=Head[i];j;j=Edge[j].Next)
		{
			int V=Edge[j].V;
			for(int p=1;p<=K;p++)
			{
				(G[p][V]+=G[p][i])%=P;
			}

		}
	}

	for(int i=1;i<=N;i++)
		for(int j=1;j<=N;j++)
			if(S[i]==1&&T[j]==1)
			{
				A[IDS[i]][IDT[j]]=G[IDS[i]][j];
			}
	Ans=Det(K);
}

void Debug()
{
	P=99999989;

	A[1][1]=3;A[1][2]=8;
	A[2][1]=1;A[2][2]=4;

	long long Ans=Det(2);
	printf("%I64d\n",Ans);
}

void Output()
{

	printf("%I64d\n",Ans);
}

int main()
{
	Init();
	Work();
	Output();
	return 0;
}


// Determinant
// 行列式（ぎょうれつしき）

#include<cstdio>
#include<algorithm>

void Get(long long &T)
{
	char C;bool F=0;
	for(;C=getchar(),C<'0'||C>'9';)if(C=='-')F=1;
	for(T=C-'0';C=getchar(),C>='0'&&C<='9';T=T*10+C-'0');
	F&&(T=-T);
}

void Get(int &T)
{
	char C;bool F=0;
	for(;C=getchar(),C<'0'||C>'9';)if(C=='-')F=1;
	for(T=C-'0';C=getchar(),C>='0'&&C<='9';T=T*10+C-'0');
	F&&(T=-T);
}

struct E
{
	int V,Next;
}Edge[100005];
int EdgeTop;
int Head[605];

void Add(int U,int V)
{
	Edge[++EdgeTop]=(E){V,Head[U]};
	Head[U]=EdgeTop;
}

int N,M;
long long P;

int Out[605];
int In[605];

void Init()
{
	Get(N);Get(M);Get(P);
	for(int i=1,U,V;i<=M;i++)
	{
		Get(U);Get(V);
		Out[U]++;
		In[V]++;
		Add(U,V);
	}
}

bool S[605];
bool T[605];

int Q[605];
int L,R;

long long G[605][605];

int K;
int IDS[605];
int IDT[605];

long long A[305][305];

long long Pow(long long X,long long Y)
{
	long long Ans=1;
	for(;Y;Y>>=1)
	{
		if(Y&1) (Ans*=X)%=P;
		(X*=X)%=P;
	}
	return Ans;
}

long long Det(int N)
{
	long long Ans=1;

	for(int i=1;i<=N;i++)
	{
		if(A[i][i]==0)
		{
			int Choose=0;
			for(int j=i+1;j<=N;j++)
				if(A[j][i]!=0)
				{
					Choose=j;
					break;
				}

			if(Choose==0) return 0;

			for(int k=i;k<=N;k++)
				std::swap(A[i][k],A[Choose][k]);

			(Ans=-Ans)%=P;
			if(Ans<0) Ans+=P;
		}

		long long Inv=Pow(A[i][i],P-2);
		(Ans*=A[i][i])%=P;
		for(int k=i;k<=N;k++)
			(A[i][k]*=Inv)%=P;

		for(int j=i+1;j<=N;j++)
		{
			long long K=A[j][i];
			for(int k=i;k<=N;k++)
			{
				(A[j][k]-=A[i][k]*K)%=P;
				if(A[j][k]<0) A[j][k]+=P;
			}
		}
	}
	return Ans;
}

long long Ans;

void Work()
{
	bool Neg;

	L=1;
	for(int i=1,k=0;i<=N;i++)
	{
		if(In[i]==0&&Out[i]==0)
		{
			Neg^=((k+K)&1);
			continue;
		}
		if(In[i]==0)
		{
			S[i]=1;
			Q[++R]=i;
			In[i]=-1;
			K++;
			IDS[i]=K;
			G[K][i]=1;
		}
		if(Out[i]==0)
		{
			T[i]=1;
			k++;
			IDT[i]=k;
		}
	}

	for(;L<=R;L++)
	{
		for(int i=Head[Q[L]];i;i=Edge[i].Next)
		{
			In[Edge[i].V]--;
			if(In[Edge[i].V]==0)
			{
				Q[++R]=Edge[i].V;
				In[Edge[i].V]=-1;
			}
		}
	}

	for(int k=1,i;k<=N;k++)
	{
		i=Q[k];

		for(int j=Head[i];j;j=Edge[j].Next)
		{
			int V=Edge[j].V;
			for(int p=1;p<=K;p++)
			{
				(G[p][V]+=G[p][i])%=P;
			}

		}
	}

	for(int i=1;i<=N;i++)
		for(int j=1;j<=N;j++)
			if(S[i]==1&&T[j]==1)
			{
				A[IDS[i]][IDT[j]]=G[IDS[i]][j];
			}

	Ans=Det(K);
	if(Neg)
	{
		(Ans=-Ans)%=P;
		if(Ans<0) Ans+=P;
	}
}

void Debug()
{
	P=99999989;

	A[1][1]=3;A[1][2]=8;
	A[2][1]=1;A[2][2]=4;

	long long Ans=Det(2);
	printf("%I64d\n",Ans);
}

void Output()
{

	printf("%I64d\n",Ans);
}

int main()
{
	Init();
	Work();
	Output();
	return 0;
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

public class E
{
    private static int MOD;
    public static void main(String [] args) throws IOException
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter writer = new PrintWriter(System.out);

        StringTokenizer tokenizer = new StringTokenizer(reader.readLine());
        int n = Integer.parseInt(tokenizer.nextToken());
        int m = Integer.parseInt(tokenizer.nextToken());
        MOD = Integer.parseInt(tokenizer.nextToken());

        ArrayList<Integer> [] rev = new ArrayList[n];
        for(int i = 0 ; i < n ; i++)
            rev[i] = new ArrayList<Integer>();

        int [] inDegree = new int[n];
        int [] outDegree = new int[n];
        for(int i = 0 ; i < m ; i++)
        {
            tokenizer = new StringTokenizer(reader.readLine());
            int a = Integer.parseInt(tokenizer.nextToken()) - 1;
            int b = Integer.parseInt(tokenizer.nextToken()) - 1;
            outDegree[a]++;
            inDegree[b]++;

            rev[b].add(a);
        }

        int k = 0;
        for(int i = 0 ; i < n ; i++)
            if(inDegree[i] == 0 && outDegree[i] != 0)
                k++;

        int [] sinks = new int[k];
        int pSink = 0;
        int [] sources = new int[k];
        int pSource = 0;

        for(int i = 0 ; i < n ; i++)
        {
            if(inDegree[i] == 0 && outDegree[i] != 0)
                sources[pSource++] = i;
            if(inDegree[i] != 0 && outDegree[i] == 0)
                sinks[pSink++] = i;
        }

        int [][] matrix = new int[k][k];
        for(int i = 0 ; i < k ; i++)
        {
            int [] calc = new int[n];
            Arrays.fill(calc, -1);
            calc[sources[i]] = 1;
            for(int j = 0 ; j < n ; j++)
                if(calc[j] == -1)
                    dfs(j, rev, calc);

            for(int j = 0 ; j < k ; j++)
                matrix[i][j] = calc[sinks[j]];
        }

        int det = determinant(matrix);

        int sign = 1;
        for(int i = 0 ; i < n ; i++)
            if(outDegree[i] == 0 && inDegree[i] == 0)
            {
                int row = Arrays.binarySearch(sources, i);
                row = -row-1;

                int col = Arrays.binarySearch(sinks, i);
                col = -col-1;

                if((row+col)%2 != 0)
                    sign *= -1;
            }

        det *= sign;
        det += MOD;
        det %= MOD;
        writer.println(det);
        writer.flush();
        writer.close();
    }

    private static int determinant(int [][] matrix)
    {
        int n = matrix.length;

        //row echelon form
        int sign = 1;
        for(int i = 0 ; i < matrix.length ; i++)
        {
            int nonZero = i;
            while(nonZero < n && matrix[nonZero][i] == 0)
                nonZero++;

            if(nonZero == n)
                return 0;

            if(nonZero != i)
                sign *= -1;

            for(int j = 0 ; j < n ; j++)
            {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[nonZero][j];
                matrix[nonZero][j] = temp;
            }

            for(int j = 0 ; j < i ; j++)
            {
                int coef = power(matrix[j][j], MOD-2);
                //coef = (int)((1L*coef*matrix[j][j])%MOD);
                coef = (int)((1L*coef*matrix[i][j])%MOD);

                for(int k = j ; k < n ; k++)
                {
                    matrix[i][k] = (int)((matrix[i][k] - 1L*matrix[j][k]*coef)%MOD);
                    matrix[i][k] += MOD;
                    matrix[i][k] %= MOD;
                }
            }
        }

        long det = 1;
        for(int i = 0 ; i < n ; i++)
        {
            det *= matrix[i][i];
            det %= MOD;
        }

        det *= sign;
        det += MOD;
        det %= MOD;
        return (int) det;
    }

    private static int power(int a, int b)
    {
        if(b == 0)
            return 1;
        if(b%2 == 1)
            return (int)((1L*a*power(a, b-1))%MOD);

        long res = power(a, b/2);
        res *= res;
        res %= MOD;
        return (int) res;
    }

    private static int dfs(int at, ArrayList<Integer> [] rev, int [] calc)
    {
        if(calc[at] != -1)
            return calc[at];

        int res = 0;
        for(int to : rev[at])
            res += dfs(to, rev, calc);

        return calc[at] = res;
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

public class E
{
    private static int MOD;
    public static void main(String [] args) throws IOException
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter writer = new PrintWriter(System.out);

        StringTokenizer tokenizer = new StringTokenizer(reader.readLine());
        int n = Integer.parseInt(tokenizer.nextToken());
        int m = Integer.parseInt(tokenizer.nextToken());
        MOD = Integer.parseInt(tokenizer.nextToken());

        ArrayList<Integer> [] rev = new ArrayList[n];
        for(int i = 0 ; i < n ; i++)
            rev[i] = new ArrayList<Integer>();

        int [] inDegree = new int[n];
        int [] outDegree = new int[n];
        for(int i = 0 ; i < m ; i++)
        {
            tokenizer = new StringTokenizer(reader.readLine());
            int a = Integer.parseInt(tokenizer.nextToken()) - 1;
            int b = Integer.parseInt(tokenizer.nextToken()) - 1;
            outDegree[a]++;
            inDegree[b]++;

            rev[b].add(a);
        }

        int k = 0;
        for(int i = 0 ; i < n ; i++)
            if(inDegree[i] == 0 && outDegree[i] != 0)
                k++;

        int [] sinks = new int[k];
        int pSink = 0;
        int [] sources = new int[k];
        int pSource = 0;

        for(int i = 0 ; i < n ; i++)
        {
            if(inDegree[i] == 0 && outDegree[i] != 0)
                sources[pSource++] = i;
            if(inDegree[i] != 0 && outDegree[i] == 0)
                sinks[pSink++] = i;
        }

        int [][] matrix = new int[k][k];
        for(int i = 0 ; i < k ; i++)
        {
            int [] calc = new int[n];
            Arrays.fill(calc, -1);
            calc[sources[i]] = 1;
            for(int j = 0 ; j < n ; j++)
                if(calc[j] == -1)
                    dfs(j, rev, calc);

            for(int j = 0 ; j < k ; j++)
                matrix[i][j] = calc[sinks[j]];
        }

        int det = determinant(matrix);

        int sign = 1;
        for(int i = 0 ; i < n ; i++)
            if(outDegree[i] == 0 && inDegree[i] == 0)
            {
                int row = Arrays.binarySearch(sources, i);
                row = -row-1;

                int col = Arrays.binarySearch(sinks, i);
                col = -col-1;

                if((row+col)%2 != 0)
                    sign *= -1;
            }

        det *= sign;
        det += MOD;
        det %= MOD;
        writer.println(det);
        writer.flush();
        writer.close();
    }

    private static int determinant(int [][] matrix)
    {
        int n = matrix.length;

        //row echelon form
        int sign = 1;
        for(int i = 0 ; i < matrix.length ; i++)
        {
            int nonZero = i;
            while(nonZero < n && matrix[nonZero][i] == 0)
                nonZero++;

            if(nonZero == n)
                return 0;

            if(nonZero != i)
                sign *= -1;

            for(int j = 0 ; j < n ; j++)
            {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[nonZero][j];
                matrix[nonZero][j] = temp;
            }

            for(int j = 0 ; j < i ; j++)
            {
                int coef = power(matrix[j][j], MOD-2);
                //coef = (int)((1L*coef*matrix[j][j])%MOD);
                coef = (int)((1L*coef*matrix[i][j])%MOD);

                for(int k = j ; k < n ; k++)
                {
                    matrix[i][k] = (int)((matrix[i][k] - 1L*matrix[j][k]*coef)%MOD);
                    matrix[i][k] += MOD;
                    matrix[i][k] %= MOD;
                }
            }
        }

        long det = 1;
        for(int i = 0 ; i < n ; i++)
        {
            det *= matrix[i][i];
            det %= MOD;
        }

        det *= sign;
        det += MOD;
        det %= MOD;
        return (int) det;
    }

    private static int power(int a, int b)
    {
        if(b == 0)
            return 1;
        if(b%2 == 1)
            return (int)((1L*a*power(a, b-1))%MOD);

        long res = power(a, b/2);
        res *= res;
        res %= MOD;
        return (int) res;
    }

    private static int dfs(int at, ArrayList<Integer> [] rev, int [] calc)
    {
        if(calc[at] != -1)
            return calc[at];

        int res = 0;
        for(int to : rev[at])
        {
            res += dfs(to, rev, calc);
            if(res >= MOD)
                res -= MOD;
        }

        return calc[at] = res;
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

public class E
{
    private static int MOD;
    public static void main(String [] args) throws IOException
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter writer = new PrintWriter(System.out);

        StringTokenizer tokenizer = new StringTokenizer(reader.readLine());
        int n = Integer.parseInt(tokenizer.nextToken());
        int m = Integer.parseInt(tokenizer.nextToken());
        MOD = Integer.parseInt(tokenizer.nextToken());

        ArrayList<Integer> [] rev = new ArrayList[n];
        for(int i = 0 ; i < n ; i++)
            rev[i] = new ArrayList<Integer>();

        int [] inDegree = new int[n];
        int [] outDegree = new int[n];
        for(int i = 0 ; i < m ; i++)
        {
            tokenizer = new StringTokenizer(reader.readLine());
            int a = Integer.parseInt(tokenizer.nextToken()) - 1;
            int b = Integer.parseInt(tokenizer.nextToken()) - 1;
            outDegree[a]++;
            inDegree[b]++;

            rev[b].add(a);
        }

        int k = 0;
        for(int i = 0 ; i < n ; i++)
            if(inDegree[i] == 0 && outDegree[i] != 0)
                k++;

        int [] sinks = new int[k];
        int pSink = 0;
        int [] sources = new int[k];
        int pSource = 0;

        for(int i = 0 ; i < n ; i++)
        {
            if(inDegree[i] == 0 && outDegree[i] != 0)
                sources[pSource++] = i;
            if(inDegree[i] != 0 && outDegree[i] == 0)
                sinks[pSink++] = i;
        }

        int [][] matrix = new int[k][k];
        for(int i = 0 ; i < k ; i++)
        {
            int [] calc = new int[n];
            Arrays.fill(calc, -1);
            calc[sources[i]] = 1;
            for(int j = 0 ; j < n ; j++)
                if(calc[j] == -1)
                    dfs(j, rev, calc);

            for(int j = 0 ; j < k ; j++)
                matrix[i][j] = calc[sinks[j]];
        }

        int det = determinant(matrix);

        int sign = 1;
        for(int i = 0 ; i < n ; i++)
            if(outDegree[i] == 0 && inDegree[i] == 0)
            {
                int row = Arrays.binarySearch(sources, i);
                row = -row-1;

                int col = Arrays.binarySearch(sinks, i);
                col = -col-1;

                if((row+col)%2 != 0)
                    sign *= -1;
            }

        det *= sign;
        det += MOD;
        det %= MOD;
        writer.println(det);
        writer.flush();
        writer.close();
    }

    private static int determinant(int [][] matrix)
    {
        int n = matrix.length;

        //row echelon form
        int sign = 1;
        for(int i = 0 ; i < matrix.length ; i++)
        {
            int nonZero = i;
            while(nonZero < n && matrix[nonZero][i] == 0)
                nonZero++;

            if(nonZero == n)
                return 0;

            if(nonZero != i)
                sign *= -1;

            for(int j = 0 ; j < n ; j++)
            {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[nonZero][j];
                matrix[nonZero][j] = temp;
            }

            int inv = power(matrix[i][i], MOD-2);

            for(int j = i+1 ; j < n ; j++)
            {
                int coef = (int)((1L*inv*matrix[j][i]));

                for(int k = i ; k < n ; k++)
                {
                    matrix[j][k] = (int)((matrix[j][k] - 1L*matrix[i][k]*coef)%MOD);
                    matrix[j][k] += MOD;
                    matrix[j][k] %= MOD;
                }
            }
        }

        long det = 1;
        for(int i = 0 ; i < n ; i++)
        {
            det *= matrix[i][i];
            det %= MOD;
        }

        det *= sign;
        det += MOD;
        det %= MOD;
        return (int) det;
    }

    private static int power(int a, int b)
    {
        if(b == 0)
            return 1;
        if(b%2 == 1)
            return (int)((1L*a*power(a, b-1))%MOD);

        long res = power(a, b/2);
        res *= res;
        res %= MOD;
        return (int) res;
    }

    private static int dfs(int at, ArrayList<Integer> [] rev, int [] calc)
    {
        if(calc[at] != -1)
            return calc[at];

        int res = 0;
        for(int to : rev[at])
        {
            res += dfs(to, rev, calc);
            if(res >= MOD)
                res -= MOD;
        }

        return calc[at] = res;
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

public class E
{
    private static int MOD;
    public static void main(String [] args) throws IOException
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter writer = new PrintWriter(System.out);

        StringTokenizer tokenizer = new StringTokenizer(reader.readLine());
        int n = Integer.parseInt(tokenizer.nextToken());
        int m = Integer.parseInt(tokenizer.nextToken());
        MOD = Integer.parseInt(tokenizer.nextToken());

        ArrayList<Integer> [] rev = new ArrayList[n];
        for(int i = 0 ; i < n ; i++)
            rev[i] = new ArrayList<Integer>();

        int [] inDegree = new int[n];
        int [] outDegree = new int[n];
        for(int i = 0 ; i < m ; i++)
        {
            tokenizer = new StringTokenizer(reader.readLine());
            int a = Integer.parseInt(tokenizer.nextToken()) - 1;
            int b = Integer.parseInt(tokenizer.nextToken()) - 1;
            outDegree[a]++;
            inDegree[b]++;

            rev[b].add(a);
        }

        int k = 0;
        for(int i = 0 ; i < n ; i++)
            if(inDegree[i] == 0 && outDegree[i] != 0)
                k++;

        int [] sinks = new int[k];
        int pSink = 0;
        int [] sources = new int[k];
        int pSource = 0;

        for(int i = 0 ; i < n ; i++)
        {
            if(inDegree[i] == 0 && outDegree[i] != 0)
                sources[pSource++] = i;
            if(inDegree[i] != 0 && outDegree[i] == 0)
                sinks[pSink++] = i;
        }

        int [][] matrix = new int[k][k];
        for(int i = 0 ; i < k ; i++)
        {
            int [] calc = new int[n];
            Arrays.fill(calc, -1);
            calc[sources[i]] = 1;
            for(int j = 0 ; j < n ; j++)
                if(calc[j] == -1)
                    dfs(j, rev, calc);

            for(int j = 0 ; j < k ; j++)
                matrix[i][j] = calc[sinks[j]];
        }

        int det = determinant(matrix);

        int sign = 1;
        for(int i = 0 ; i < n ; i++)
            if(outDegree[i] == 0 && inDegree[i] == 0)
            {
                int row = Arrays.binarySearch(sources, i);
                row = -row-1;

                int col = Arrays.binarySearch(sinks, i);
                col = -col-1;

                if((row+col)%2 != 0)
                    sign *= -1;
            }

        det *= sign;
        det += MOD;
        det %= MOD;
        writer.println(det);
        writer.flush();
        writer.close();
    }

    private static int determinant(int [][] matrix)
    {
        int n = matrix.length;

        //row echelon form
        int sign = 1;
        for(int i = 0 ; i < matrix.length ; i++)
        {
            int nonZero = i;
            while(nonZero < n && matrix[nonZero][i] == 0)
                nonZero++;

            if(nonZero == n)
                return 0;

            if(nonZero != i)
                sign *= -1;

            for(int j = 0 ; j < n ; j++)
            {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[nonZero][j];
                matrix[nonZero][j] = temp;
            }

            int inv = power(matrix[i][i], MOD-2);

            for(int j = i+1 ; j < n ; j++)
            {
                int coef = (int)((1L*inv*matrix[j][i])%MOD);

                for(int k = i ; k < n ; k++)
                {
                    matrix[j][k] = (int)((matrix[j][k] - 1L*matrix[i][k]*coef)%MOD);
                    matrix[j][k] += MOD;
                    matrix[j][k] %= MOD;
                }
            }
        }

        long det = 1;
        for(int i = 0 ; i < n ; i++)
        {
            det *= matrix[i][i];
            det %= MOD;
        }

        det *= sign;
        det += MOD;
        det %= MOD;
        return (int) det;
    }

    private static int power(int a, int b)
    {
        if(b == 0)
            return 1;
        if(b%2 == 1)
            return (int)((1L*a*power(a, b-1))%MOD);

        long res = power(a, b/2);
        res *= res;
        res %= MOD;
        return (int) res;
    }

    private static int dfs(int at, ArrayList<Integer> [] rev, int [] calc)
    {
        if(calc[at] != -1)
            return calc[at];

        int res = 0;
        for(int to : rev[at])
        {
            res += dfs(to, rev, calc);
            if(res >= MOD)
                res -= MOD;
        }

        return calc[at] = res;
    }
}