use std::{collections::BinaryHeap, cmp::Reverse}; const MOD: usize = 1e9 as usize + 7; fn topologycal_sort(paths: &Vec>) -> Vec { let n = paths.len(); let mut ret = vec![]; let mut ins = vec![0usize; n]; for i in 0..n { for &v in paths[i].iter() { ins[v] += 1; } } let mut que = BinaryHeap::new(); for i in 0..n { if ins[i] == 0 { que.push(Reverse(i)); } } while let Some(Reverse(x)) = que.pop() { ret.push(x); for &v in paths[x].iter() { ins[v] -= 1; if ins[v] == 0 { que.push(Reverse(v)); } } } ret } fn main() { let mut nm = String::new(); std::io::stdin().read_line(&mut nm).ok(); let nm: Vec = nm.trim().split_whitespace().map(|s| s.parse().unwrap()).collect(); let n = nm[0]; let m = nm[1]; let mut paths_for_dag = vec![vec![]; n+1]; let mut paths = vec![vec![]; n+1]; for _ in 0..m { let mut temp = String::new(); std::io::stdin().read_line(&mut temp).ok(); let temp: Vec = temp.trim().split_whitespace().map(|s| s.parse().unwrap()).collect(); let u = temp[0]; let v = temp[1]; let l = temp[2]; let a = temp[3]; paths_for_dag[u].push(v); paths[u].push((v, l, a)); } let temp = topologycal_sort(&paths_for_dag); if temp.len() < n+1 { println!("INF"); return; } let mut cnts = vec![0usize; n+1]; for &u in temp.iter() { for &(v, l, a) in paths[u].iter() { cnts[v] += l * a + cnts[u]; cnts[v] %= MOD; } } println!("{}", cnts[n]); }