import sys # sys.setrecursionlimit(200005) int1 = lambda x: int(x)-1 p2D = lambda x: print(*x, sep="\n") def II(): return int(sys.stdin.readline()) def LI(): return list(map(int, sys.stdin.readline().split())) def LI1(): return list(map(int1, sys.stdin.readline().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def LLI1(rows_number): return [LI1() for _ in range(rows_number)] def SI(): return sys.stdin.readline().rstrip() # dij = [(0, 1), (-1, 0), (0, -1), (1, 0)] dij = [(0, 1), (1, 0), (0, -1), (-1, 0)] # dij = [(0, 1), (-1, 0), (0, -1), (1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)] inf = 1 << 63 # md = 998244353 md = 10**9+7 # 各強連結成分をリストにしてトポロジカル順に返す def SCC(to, ot): n = len(to) # トポロジカルソート fin = [-1]*n topo = [] for u in range(n): if fin[u] != -1: continue stack = [u] while stack: u = stack[-1] if fin[u] == -1: fin[u] = 0 for v, _, _ in to[u]: if fin[v] != -1: continue stack.append(v) else: stack.pop() if fin[u] == 0: fin[u] = 1 topo.append(u) # 逆辺でdfs res = [] while topo: u = topo.pop() if fin[u] != 1: continue fin[u] = 2 cur = [u] i = 0 while i < len(cur): u = cur[i] for v, _, _ in ot[u]: if fin[v] == 2: continue fin[v] = 2 cur.append(v) i += 1 res.append(cur) return res n, m = LI() to = [[] for _ in range(n+1)] ot = [[] for _ in range(n+1)] for i in range(m): u, v, l, a = LI() to[u].append((v, l, a)) ot[v].append((u, l, a)) gg = SCC(to, ot) gn = len(gg) # print(gg) utog = [-1]*(n+1) for g, uu in enumerate(gg): for u in uu: utog[u] = g # print(utog) to2 = [[] for _ in range(gn)] ot2 = [[] for _ in range(gn)] for u in range(n+1): g = utog[u] for v, l, a in to[u]: h = utog[v] if g == h: continue to2[g].append((h, l, a)) ot2[h].append((g, l, a)) # print(to2, ot2) def reach(g, to): res = [False]*gn res[g] = True stack = [g] while stack: g = stack.pop() for h, _, _ in to[g]: if res[h]: continue res[h] = True stack.append(h) return res s = utog[0] t = utog[n] r1 = reach(s, to2) r2 = reach(t, ot2) # print(r1, r2) rem = [False]*gn for g in range(gn): if r1[g] and r2[g]: if len(gg[g]) > 1: print("INF") exit() else: rem[g] = True dd = [0]*gn cc = [0]*gn cc[t] = 1 for g in range(t-1, s-1, -1): if rem[g]: continue for h, l, a in to2[g]: if rem[h]: continue c = cc[h]*a%md cc[g] += c dd[g] += c*l%md+dd[h] cc[g] %= md dd[g] %= md print(dd[s])