using System; using static System.Console; using System.Linq; using System.Collections.Generic; class Program { static int NN => int.Parse(ReadLine()); static int[] NList => ReadLine().Split().Select(int.Parse).ToArray(); static int[][] NArr(long n) => Enumerable.Repeat(0, (int)n).Select(_ => NList).ToArray(); public static void Main() { Solve(); } static void Solve() { var c = NList; var (n, m) = (c[0], c[1]); ++n; var map = NArr(m); var tree = new List<(int to, long len, long count)>[n]; for (var i = 0; i < tree.Length; ++i) tree[i] = new List<(int to, long len, long count)>(); var revtree = new List[n]; for (var i = 0; i < revtree.Length; ++i) revtree[i] = new List(); var refs = new int[n]; foreach (var edge in map) { tree[edge[0]].Add((edge[1], edge[2], edge[3])); revtree[edge[1]].Add(edge[0]); ++refs[edge[1]]; } var visited = new bool[n]; var lengths = new long[n]; var counts = new long[n]; counts[0] = 1; var mod = 1_000_000_007; var q = new Queue(); for (var i = 0; i < n; ++i) if (refs[i] == 0) { visited[i] = true; q.Enqueue(i); } while (q.Count > 0) { var cur = q.Dequeue(); foreach (var next in tree[cur]) { counts[next.to] = (counts[next.to] + counts[cur] * next.count % mod) % mod; lengths[next.to] = (lengths[next.to] + counts[cur] * next.len % mod * next.count % mod + lengths[cur] * next.count % mod) % mod; --refs[next.to]; if (refs[next.to] == 0) { visited[next.to] = true; q.Enqueue(next.to); } } } var reachable0 = new bool[n]; DFS(0, tree, reachable0); var reachableN = new bool[n]; DFS(n - 1, revtree, reachableN); for (var i = 0; i < n; ++i) if (reachable0[i] && reachableN[i] && !visited[i]) { WriteLine("INF"); return; } WriteLine(lengths[^1]); } static void DFS(int cur, List<(int to, long len, long count)>[] tree, bool[] visited) { visited[cur] = true; foreach (var next in tree[cur]) { if (visited[next.to]) continue; DFS(next.to, tree, visited); } } static void DFS(int cur, List[] tree, bool[] visited) { visited[cur] = true; foreach (var next in tree[cur]) { if (visited[next]) continue; DFS(next, tree, visited); } } static long Exp(long n, long p, int mod) { long _n = n % mod; var _p = p; var result = 1L; if ((_p & 1) == 1) result *= _n; while (_p > 0) { _n = _n * _n % mod; _p >>= 1; if ((_p & 1) == 1) result = result * _n % mod; } return result; } }