import sys input = sys.stdin.buffer.readline def topological_sorted(digraph): n = len(digraph) indegree = [0] * n for v in range(n): for nxt_v in digraph[v]: indegree[nxt_v] += 1 tp_order = [i for i in range(n) if indegree[i] == 0] stack = tp_order[:] while stack: v = stack.pop() for nxt_v in digraph[v]: indegree[nxt_v] -= 1 if indegree[nxt_v] == 0: stack.append(nxt_v) tp_order.append(nxt_v) return len(tp_order) == n, tp_order n, m = map(int, input().split()) edges = [list(map(int, input().split())) for i in range(m)] MOD = 10 ** 9 + 7 graph = [[] for i in range(n + 1)] for u, v, _, _ in edges: graph[u].append(v) rev_graph = [[] for i in range(n + 1)] for u, v, _, _ in edges: rev_graph[v].append(u) root = 0 reach = [False] * (n + 1) reach[0] = True stack = [root] while stack: v = stack.pop() for nxt_v in graph[v]: if reach[nxt_v]: continue reach[nxt_v] = True stack.append(nxt_v) root = n rev_reach = [False] * (n + 1) rev_reach[n] = True stack = [root] while stack: v = stack.pop() for nxt_v in rev_graph[v]: if rev_reach[nxt_v]: continue rev_reach[nxt_v] = True stack.append(nxt_v) if not reach[n]: print(0) exit() for i in range(n + 1): reach[i] = reach[i] & rev_reach[i] graph = [set() for i in range(n + 1)] memo = {} for u, v, l, a in edges: if reach[u] and reach[v]: graph[u].add(v) if (u, v) not in memo: memo[u, v] = [] memo[u, v].append((l, a)) flag, tp_order = topological_sorted(graph) if not flag: print("INF") exit() nxt_ptn = [0] * (n + 1) nxt_ptn[n] = 1 for v in tp_order[::-1]: for nxt_v in graph[v]: for l, a in memo[v, nxt_v]: nxt_ptn[v] += nxt_ptn[nxt_v] * a nxt_ptn[v] %= MOD ans = 0 ptn = [0] * (n + 1) ptn[0] = 1 for v in tp_order: for nxt_v in graph[v]: for l, a in memo[v, nxt_v]: ptn[nxt_v] += ptn[v] * a ans += ptn[v] * nxt_ptn[nxt_v] * l * a ptn[nxt_v] %= MOD ans %= MOD print(ans)