Problem:
Score : 400 points

Problem Statement

There are N people standing on the x-axis.
Let the coordinate of Person i be x_i.
For every i, x_i is an integer between 0 and 10^9 (inclusive).
It is possible that more than one person is standing at the same coordinate.

You will given M pieces of information regarding the positions of these people.
The i-th piece of information has the form (L_i, R_i, D_i).
This means that Person R_i is to the right of Person L_i by D_i units of distance, that is, x_{R_i} - x_{L_i} = D_i holds.

It turns out that some of these M pieces of information may be incorrect.
Determine if there exists a set of values (x_1, x_2, ..., x_N) that is consistent with the given pieces of information.

Constraints

1 \leq N \leq 100 000

0 \leq M \leq 200 000

1 \leq L_i, R_i \leq N (1 \leq i \leq M)

0 \leq D_i \leq 10 000 (1 \leq i \leq M)

L_i \neq R_i (1 \leq i \leq M)

If i \neq j, then (L_i, R_i) \neq (L_j, R_j) and (L_i, R_i) \neq (R_j, L_j).

D_i are integers.

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1 D_1
L_2 R_2 D_2
:
L_M R_M D_M

Output

If there exists a set of values (x_1, x_2, ..., x_N) that is consistent with all given pieces of information, print Yes; if it does not exist, print No.

Sample Input 1

3 3
1 2 1
2 3 1
1 3 2

Sample Output 1

Yes

Some possible sets of values (x_1, x_2, x_3) are (0, 1, 2) and (101, 102, 103).

Sample Input 2

3 3
1 2 1
2 3 1
1 3 5

Sample Output 2

No

If the first two pieces of information are correct, x_3 - x_1 = 2 holds, which is contradictory to the last piece of information.

Sample Input 3

4 3
2 1 1
2 3 5
3 4 2

Sample Output 3

Yes

Sample Input 4

10 3
8 7 100
7 9 100
9 8 100

Sample Output 4

No

Sample Input 5

100 0

Sample Output 5

Yes

Solution in Rust (1.15.1) (judge verdict: Wrong Answer)

macro_rules! semigroup_impl {
  ($marker:ty, $t:ty, | $lhs:ident, $rhs:ident | $append:expr) => {
    impl $crate::math::algebra::Semigroup for $marker {
      type T = $t;

      fn append($lhs: &$t, $rhs: &$t) -> $t {
        $append
      }
    }
  };
}

macro_rules! monoid_impl {
  ($marker:ty, $t:ty, | $lhs:ident, $rhs:ident | $append:expr, $identity:expr) => {
    semigroup_impl! { $marker, $t, |$lhs, $rhs| $append }

    impl $crate::math::algebra::Monoid for $marker {
      fn identity() -> $t {
        $identity
      }
    }
  };
}

macro_rules! group_impl {
  ($marker:ty, $t:ty, | $lhs:ident, $rhs:ident | $append:expr, | $x:ident | $invert:expr, $identity:expr) => {
    monoid_impl! { $marker, $t, |$lhs, $rhs| $append, $identity }

    impl $crate::math::algebra::Group for $marker {
      fn invert($x: &$t) -> $t {
        $invert
      }
    }
  };
}

macro_rules! commutative_monoid_impl {
  ($marker:ty, $t:ty, | $lhs:ident, $rhs:ident | $append:expr, $identity:expr) => {
    monoid_impl! { $marker, $t, |$lhs, $rhs| $append, $identity }

    impl $crate::math::algebra::CommutativeMonoid for $marker {}
  };
}

macro_rules! commutative_group_impl {
  ($marker:ty, $t:ty, | $lhs:ident, $rhs:ident | $append:expr, | $x:ident | $invert:expr, $identity:expr) => {
    group_impl! { $marker, $t, |$lhs, $rhs| $append, |$x| $invert, $identity }

    impl $crate::math::algebra::CommutativeMonoid for $marker {}

    impl $crate::math::algebra::CommutativeGroup for $marker {}
  };
}

fn solve<R: BufRead, W: Write>(_reader: R, _writer: &mut W) {
  let mut _scanner = Scanner::new(_reader);

  #[allow(unused_macros)]
  macro_rules! scan {
    ($t:ty) => {
      _scanner.next::<$t>().unwrap()
    };
    ($($t:ty),+) => {
      ($(scan!($t)),+)
    };
    ($t:ty; $n:expr $(; $m:expr)*) => {{
      let mut vec = Vec::with_capacity($n);
      for _ in 0..$n {
        vec.push(scan!($t $(; $m)*));
      }
      vec
    }};
    ($t_0:ty, $t_1:ty; $n:expr) => {
      scan!($t_0 = 0, $t_1 = 1; $n)
    };
    ($t_0:ty, $t_1:ty, $t_2:ty; $n:expr) => {
      scan!($t_0 = 0, $t_1 = 1, $t_2 = 2; $n)
    };
    ($($t:ty = $i:tt),+; $n:expr) => {{
      let mut vecs = ($(Vec::<$t>::with_capacity($n)),+);
      for _ in 0..$n {$(
        vecs.$i.push(scan!($t));
      )+}
      vecs
    }};
  }

  #[allow(unused_macros)]
  macro_rules! scan_iter {
    ($t:ty; $n:expr) => {
      _scanner.take::<$t>($n).map(|x| x.unwrap())
    };
  }

  #[allow(unused_macros)]
  macro_rules! print {
    ($fmt:expr) => {
      write!(_writer, $fmt).unwrap()
    };
    ($fmt:expr, $($arg:tt)*) => {
      write!(_writer, $fmt, $($arg)*).unwrap()
    };
  }

  #[allow(unused_macros)]
  macro_rules! println {
    () => {
      writeln!(_writer).unwrap()
    };
    ($fmt:expr) => {
      writeln!(_writer, $fmt).unwrap()
    };
    ($fmt:expr, $($arg:tt)*) => {
      writeln!(_writer, $fmt, $($arg)*).unwrap()
    };
  }

  #[allow(unused_macros)]
  macro_rules! eprint {
    ($fmt:expr) => {
      #[cfg(debug_assertions)]
      write!(::std::io::stderr(), $fmt).unwrap()
    };
    ($fmt:expr, $($arg:tt)*) => {
      #[cfg(debug_assertions)]
      write!(::std::io::stderr(), $fmt, $($arg)*).unwrap()
    };
  }

  #[allow(unused_macros)]
  macro_rules! eprintln {
    () => {
      #[cfg(debug_assertions)]
      writeln!(::std::io::stderr()).unwrap()
    };
    ($fmt:expr) => {
      #[cfg(debug_assertions)]
      writeln!(::std::io::stderr(), $fmt).unwrap()
    };
    ($fmt:expr, $($arg:tt)*) => {
      #[cfg(debug_assertions)]
      writeln!(::std::io::stderr(), $fmt, $($arg)*).unwrap()
    };
  }

  #[allow(unused_macros)]
  macro_rules! dump {
    ($($x:expr),+) => {
      eprint!("[{}:{}] ", file!(), line!());
      eprintln!(concat!($(stringify!($x), "={:?}; "),+), $($x),+);
    };
  }

  use data_structures::PotentializedUnionFindTree;
  use math::algebra::AdditiveGroup;

  let (n, m) = scan!(usize, usize);
  let mut uf = PotentializedUnionFindTree::<AdditiveGroup<i64>>::new(n);
  for _ in 0..m {
    let (l, r, d) = scan!(usize, usize, i64);
    let (l, r) = (l - 1, r - 1);
    if let Some(potential_diff) = uf.potential_diff(l, r) {
      if potential_diff != d {
        println!("No");
        return;
      }
    } else {
      uf.unite(l, r, &d);
    }
  }
  println!("Yes");
}

const STACK_SIZE_MEBIBYTES: Option<usize> = None;

fn main() {
  fn run_solver() {
    let stdin = stdin();
    let stdout = stdout();
    #[cfg(debug_assertions)]
    let mut writer = stdout.lock();
    #[cfg(not(debug_assertions))]
    let mut writer = ::std::io::BufWriter::new(stdout.lock());
    solve(stdin.lock(), &mut writer);
    writer.flush().unwrap();
  }
  if let Some(size) = STACK_SIZE_MEBIBYTES {
    let builder = ::std::thread::Builder::new().stack_size(size * 1024 * 1024);
    builder.spawn(run_solver).unwrap().join().unwrap();
  } else {
    run_solver();
  }
}

use io::Scanner;
use std::io::{stdin, stdout, BufRead, Write};

pub mod math {
  pub mod algebra {
    pub use self::additive_group::*;
    pub use self::commutative_group::*;
    pub use self::commutative_monoid::*;
    pub use self::group::*;
    pub use self::monoid::*;
    pub use self::semigroup::*;

    mod semigroup {
      use std::fmt::Debug;

      pub trait Semigroup {
        type T: Clone + PartialEq + Debug;

        fn append(lhs: &Self::T, rhs: &Self::T) -> Self::T;

        fn append_assign(lhs: &mut Self::T, rhs: &Self::T) {
          *lhs = Self::append(lhs, rhs);
        }
      }
    }

    mod monoid {
      use math::algebra::Semigroup;

      pub trait Monoid: Semigroup {
        fn identity() -> Self::T;
      }
    }

    mod group {
      use math::algebra::Monoid;

      pub trait Group: Monoid {
        fn invert(&Self::T) -> Self::T;

        fn append_inverse(lhs: &Self::T, rhs: &Self::T) -> Self::T {
          Self::append(lhs, &Self::invert(rhs))
        }

        fn append_inverse_assign(lhs: &mut Self::T, rhs: &Self::T) {
          *lhs = Self::append_inverse(lhs, rhs);
        }
      }
    }

    mod commutative_monoid {
      use math::algebra::Monoid;

      pub trait CommutativeMonoid: Monoid {}
    }

    mod commutative_group {
      use math::algebra::{CommutativeMonoid, Group};

      pub trait CommutativeGroup: Group + CommutativeMonoid {}
    }

    mod additive_group {
      use std::marker::PhantomData;

      pub struct AdditiveGroup<T> {
        _marker: PhantomData<fn() -> T>,
      }

      macro_rules! additive_group_impl {
        ($($t:ty)+) => {$(
          commutative_group_impl! { AdditiveGroup<$t>, $t, |lhs, rhs| lhs + rhs, |x| -x, 0 }
        )+};
      }

      additive_group_impl! { i32 i64 isize }
    }
  }
}

pub mod data_structures {
  pub use self::potentialized_union_find_tree::*;

  mod potentialized_union_find_tree {
    use math::algebra::CommutativeGroup;
    use std::mem::swap;

    pub struct PotentializedUnionFindTree<G: CommutativeGroup> {
      nodes: Vec<PotentializedNode<G>>,
    }

    #[derive(Clone, Copy, Debug)]
    enum Node {
      Root { node_count: usize },
      Descendant { parent_index: usize },
    }

    struct PotentializedNode<G: CommutativeGroup> {
      node: Node,
      potential: G::T,
    }

    impl<G: CommutativeGroup> PotentializedUnionFindTree<G> {
      pub fn new(size: usize) -> Self {
        let mut nodes = Vec::with_capacity(size);
        for _ in 0..size {
          nodes.push(PotentializedNode {
            node: Node::Root { node_count: 1 },
            potential: G::identity(),
          });
        }
        PotentializedUnionFindTree { nodes: nodes }
      }

      pub fn len(&self) -> usize {
        self.nodes.len()
      }

      pub fn unite(&mut self, l_index: usize, r_index: usize, potential_diff: &G::T) -> bool {
        debug_assert!(l_index < self.len());
        debug_assert!(r_index < self.len());
        let mut l_root_index = self.find(l_index);
        let mut r_root_index = self.find(r_index);
        if l_root_index == r_root_index {
          return false;
        }
        let l_potential = self.potential_diff(l_root_index, l_index).unwrap();
        let r_potential = self.potential_diff(r_root_index, r_index).unwrap();
        let mut potential_diff = G::append_inverse(&G::append(potential_diff, &l_potential), &r_potential);
        match (self.nodes[l_root_index].node, self.nodes[r_root_index].node) {
          (Node::Root { node_count: l_node_count }, Node::Root { node_count: r_node_count }) => {
            let node_count = l_node_count + r_node_count;
            if l_node_count < r_node_count {
              swap(&mut l_root_index, &mut r_root_index);
              potential_diff = G::invert(&potential_diff);
            }
            self.nodes[l_root_index] = PotentializedNode {
              node: Node::Root { node_count: node_count },
              potential: {
                debug_assert_eq!(self.nodes[l_root_index].potential, G::identity());
                G::identity()
              },
            };
            self.nodes[r_root_index] = PotentializedNode {
              node: Node::Descendant { parent_index: l_root_index },
              potential: potential_diff,
            };
          }
          _ => unreachable!("`find` must return root index"),
        }
        true
      }

      pub fn find(&mut self, mut index: usize) -> usize {
        debug_assert!(index < self.len());
        while let Node::Descendant { parent_index } = self.nodes[index].node {
          index = if let Node::Descendant { parent_index: grandparent_index } = self.nodes[parent_index].node {
            self.nodes[index] = PotentializedNode {
              node: Node::Descendant { parent_index: grandparent_index },
              potential: G::append(&self.nodes[parent_index].potential, &self.nodes[index].potential),
            };
            grandparent_index
          } else {
            parent_index
          };
        }
        index
      }

      pub fn is_same_group(&mut self, l_index: usize, r_index: usize) -> bool {
        debug_assert!(l_index < self.len());
        debug_assert!(r_index < self.len());
        self.find(l_index) == self.find(r_index)
      }

      pub fn count_elements(&mut self, index: usize) -> usize {
        debug_assert!(index < self.len());
        let root_index = self.find(index);
        match self.nodes[root_index].node {
          Node::Root { node_count } => node_count,
          _ => unreachable!("`find` must return root index"),
        }
      }

      pub fn potential_diff(&mut self, l_index: usize, r_index: usize) -> Option<G::T> {
        debug_assert!(l_index < self.len());
        debug_assert!(r_index < self.len());
        if self.is_same_group(l_index, r_index) {
          Some(G::append_inverse(&self.nodes[r_index].potential, &self.nodes[l_index].potential))
        } else {
          None
        }
      }
    }
  }
}

pub mod io {
  pub use self::scanner::*;

  mod scanner {
    use std::io::BufRead;
    use std::marker::PhantomData;
    use std::str::{from_utf8, FromStr};

    pub struct Scanner<R> {
      reader: R,
      buffer: Vec<u8>,
      position: usize,
    }

    impl<R: BufRead> Scanner<R> {
      pub fn new(reader: R) -> Self {
        Scanner { reader: reader, buffer: vec![], position: 0 }
      }

      pub fn next<T: Parse>(&mut self) -> Option<T> {
        Parse::parse(self.next_bytes().unwrap_or(&[]))
      }

      pub fn take<T: Parse>(&mut self, n: usize) -> Take<R, T> {
        Take { scanner: self, n: n, _marker: PhantomData }
      }

      pub fn next_bytes(&mut self) -> Option<&[u8]> {
        if self.buffer.is_empty() {
          self.read_line();
        }
        loop {
          match self.buffer.get(self.position) {
            Some(&b' ') => self.position += 1,
            Some(&b'\n') => self.read_line(),
            Some(_) => break,
            None => return None,
          }
        }
        let start = self.position;
        loop {
          match self.buffer.get(self.position) {
            Some(&b' ') | Some(&b'\n') | None => break,
            Some(_) => self.position += 1,
          }
        }
        Some(&self.buffer[start..self.position])
      }

      fn read_line(&mut self) {
        self.position = 0;
        self.buffer.clear();
        self.reader.read_until(b'\n', &mut self.buffer).unwrap();
      }
    }

    pub struct Take<'a, R: 'a, T> {
      scanner: &'a mut Scanner<R>,
      n: usize,
      _marker: PhantomData<fn() -> T>,
    }

    impl<'a, R: BufRead, T: Parse> Iterator for Take<'a, R, T> {
      type Item = Option<T>;

      fn next(&mut self) -> Option<Self::Item> {
        if self.n > 0 {
          self.n -= 1;
          Some(self.scanner.next())
        } else {
          None
        }
      }

      fn size_hint(&self) -> (usize, Option<usize>) {
        (self.n, Some(self.n))
      }
    }

    impl<'a, R: BufRead, T: Parse> ExactSizeIterator for Take<'a, R, T> {}

    pub trait Parse: Sized {
      fn parse(bytes: &[u8]) -> Option<Self>;
    }

    impl Parse for u8 {
      fn parse(bytes: &[u8]) -> Option<Self> {
        if bytes.len() == 1 {
          Some(*unsafe { bytes.get_unchecked(0) })
        } else {
          None
        }
      }
    }

    macro_rules! parse_impl {
      ($($t:ident)+) => {$(
        impl Parse for $t {
          fn parse(bytes: &[u8]) -> Option<Self> {
            from_utf8(bytes).ok().and_then(|s| $t::from_str(s).ok())
          }
        }
      )+};
    }

    parse_impl! { i32 i64 isize u32 u64 usize String }
  }
}