import numpy as np import sys int1 = lambda x: int(x) - 1 def MI(): return map(int, sys.stdin.readline().split()) def LI(): return list(map(int1, sys.stdin.readline().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def main(n): if n == 3: ans = 0 for p, q, r in pqr: if p == 0 and r == 0: ans += 1 print(ans) exit() to = np.zeros((36, 36), dtype=object) #print(pqr) for p,q,r in pqr:to[p*6+q][q*6+r]=1 #print(to) cnt = np.eye(36, dtype=object) n -= 2 while n: if n & 1: cnt = np.dot(cnt, to) % md to = np.dot(to, to) % md n >>= 1 #print(cnt) ans = 0 for i in range(6): for j in range(6): ans += cnt[i][j*6] ans %= md print(ans) md=10**9+7 k,m,n=MI() pqr=LLI(m) main(n)