Problem:
Weighted Union Find Trees

There is a sequence $A = a_0, a_1, ..., a_{n-1}$. You are given the following information and questions.

relate$(x, y, z)$: $a_y$ is greater than $a_x$ by $z$

diff$(x, y)$: report the difference between $a_x$ and $a_y$ $(a_y - a_x)$

Input

$n \; q$
$query_1$
$query_2$
:
$query_q$

In the first line, $n$ and $q$ are given. Then, $q$ information/questions are given in the following format.

0 $x \; y\; z$

or

1 $x \; y$

where '0' of the first digit denotes the relate information and '1' denotes the diff question.

Output

For each diff question, print the difference between $a_x$ and $a_y$ $(a_y - a_x)$.

Constraints

$2 \leq n \leq 100,000$

$1 \leq q \leq 200,000$

$0 \leq x, y < n$

$x \ne y$

$0 \leq z \leq 10000$

There are no inconsistency in the given information

Sample Input

5 6
0 0 2 5
0 1 2 3
1 0 1
1 1 3
0 1 4 8
1 0 4

Sample Output

2
?
10

Solution in Rust (judge verdict: Accepted)

#[allow(unused_imports)]
use std::cmp::{min,max};
#[allow(unused_imports)]
use std::collections::{BTreeMap,BTreeSet};
#[allow(unused_imports)]
use std::ops::*;
#[allow(unused_imports)]
use std::collections::BinaryHeap;

use std::collections::VecDeque;

#[allow(unused_macros)]
macro_rules! ite {
    ($c:expr, $t:expr, $f:expr) => {{
        if $c { $t } else { $f }
    }};
}

struct WeightedUnionFindNode {
    parent: usize,
    dist_to_parent: i64,
    num: usize,
}

impl WeightedUnionFindNode {
    fn new(parent: usize) -> WeightedUnionFindNode {
        WeightedUnionFindNode {
            parent: parent,
            dist_to_parent: 0,
            num: 1,
        }
    }
}

pub struct WeightedUnionFind(Vec<WeightedUnionFindNode>);

impl WeightedUnionFind {
    pub fn new(n: usize) -> WeightedUnionFind {
        let mut xs = vec![];
        for i in 0..n {
            xs.push(WeightedUnionFindNode::new(i));
        }
        WeightedUnionFind(xs)
    }
    pub fn root(&mut self, i: usize) -> (usize, i64) {
        let parent = self.0[i].parent;
        if parent == i {
            (i, 0)
        } else {
            let (new_parent, dist_to_parent) = self.root(parent);
            let new_dist_to_parent = self.0[i].dist_to_parent + dist_to_parent;
            self.0[i].parent = new_parent;
            self.0[i].dist_to_parent = new_dist_to_parent;
            (new_parent, new_dist_to_parent)
        }
    }
    pub fn unite(&mut self, i: usize, k: usize, w: i64) {
        let (i,d_i) = self.root(i);
        let (k,d_k) = self.root(k);
        if i == k {
            return;
        }
        if self.0[i].num < self.0[k].num {
            let d = w - (d_i - d_k);
            self.0[i].parent = k;
            self.0[i].dist_to_parent = d;
            self.0[k].num += self.0[i].num;
        } else {
            let d = -(w - (d_i - d_k));
            self.0[k].parent = i;
            self.0[k].dist_to_parent = d;
            self.0[i].num += self.0[k].num;
        }
    }
    pub fn is_same_set(&mut self, i: usize, k: usize) -> bool {
        self.root(i).0 == self.root(k).0
    }
    pub fn dist(&mut self, i: usize, k: usize) -> Option<i64> {
        let (ri, d_i) = self.root(i);
        let (rk, d_k) = self.root(k);
        if ri == rk {
            Some(d_i - d_k)
        }
        else {
            None
        }
    }
}

// ref: tanakh <https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8>
// diff: using Parser
#[macro_export]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut parser = Parser::from_str($s);
        input_inner!{parser, $($r)*}
    };
    (parser = $parser:ident, $($r:tt)*) => {
        input_inner!{$parser, $($r)*}
    };
    (new_stdin_parser = $parser:ident, $($r:tt)*) => {
        let stdin = std::io::stdin();
        let reader = std::io::BufReader::new(stdin.lock());
        let mut $parser = Parser::new(reader);
        input_inner!{$parser, $($r)*}
    };
    ($($r:tt)*) => {
        input!{new_stdin_parser = parser, $($r)*}
    };
}

#[macro_export]
macro_rules! input_inner {
    ($parser:ident) => {};
    ($parser:ident, ) => {};
    ($parser:ident, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($parser, $t);
        input_inner!{$parser $($r)*}
    };
}

#[macro_export]
macro_rules! read_value {
    ($parser:ident, ( $($t:tt),* )) => {
        ( $(read_value!($parser, $t)),* )
    };
    ($parser:ident, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($parser, $t)).collect::<Vec<_>>()
    };
    ($parser:ident, chars) => {
        read_value!($parser, String).chars().collect::<Vec<char>>()
    };
    ($parser:ident, usize1) => {
        read_value!($parser, usize) - 1
    };
    ($parser:ident, $t:ty) => {
        $parser.next::<$t>().expect("Parse error")
    };
}

fn main() {
    input! {
        new_stdin_parser = parser,
        n: usize,
        q: usize,
    }
    let mut wuf = WeightedUnionFind::new(n);
    for _ in 0..q {
        input! {
            parser = parser,
            command: usize,
        }
        if command == 0 {
            input! {
                parser = parser,
                i: usize,
                k: usize,
                w: i64,
            }
            wuf.unite(i, k, w);
        } else {
            input! {
                parser = parser,
                i: usize,
                k: usize,
            }
            match wuf.dist(i, k) {
                Some(d) => {
                    println!("{}", d);
                }
                None => {
                    println!("?");
                }
            }
        }
    }
}

use std::io::BufRead;
use std::io;
use std::str;

// ref: tatsuya6502 <https://qiita.com/tatsuya6502/items/cd448486f7ef7b5b8c7e>
// ref: wariuni <https://qiita.com/tatsuya6502/items/cd448486f7ef7b5b8c7e#comment-7040a5ae96305e884eb9>
// diff: using std::io::BufRead::fill_buf()
pub struct Parser<R> {
    reader: R,
    buf: Vec<u8>,
    pos: usize,
}

impl Parser<io::Empty> {
    pub fn from_str(s: &str) -> Parser<io::Empty> {
        Parser {
            reader: io::empty(),
            buf: s.as_bytes().to_vec(),
            pos: 0,
        }
    }
}

impl<R:BufRead> Parser<R> {
    pub fn new(reader: R) -> Parser<R> {
        Parser {
            reader: reader,
            buf: vec![],
            pos: 0,
        }
    }
    pub fn update_buf(&mut self) {
        self.buf.clear();
        self.pos = 0;
        loop {
            let (len,complete) = {
                let buf2 = self.reader.fill_buf().unwrap();
                self.buf.extend_from_slice(buf2);
                let len = buf2.len();
                (len, buf2[len-1] <= 0x20)
            };
            self.reader.consume(len);
            if complete {
                break;
            }
        }
    }
    pub fn next<T:str::FromStr>(&mut self) -> Result<T, T::Err> {
        loop {
            let mut begin = self.pos;
            while begin < self.buf.len() && (self.buf[begin] <= 0x20) {
                begin += 1;
            }
            let mut end = begin;
            while end < self.buf.len() && (self.buf[end] > 0x20) {
                end += 1;
            }
            if begin != self.buf.len() {
                self.pos = end;
                return str::from_utf8(&self.buf[begin..end]).unwrap().parse::<T>();
            }
            else {
                self.update_buf();
            }
        }
    }
}

use std::fmt::Display;
#[allow(dead_code)]
fn write_vec<T: Display>(xs: &Vec<T>) {
    if xs.len() == 0 {
        println!();
        return;
    }
    print!("{}", xs[0]);
    for i in 1..xs.len() {
        print!(" {}", xs[i]);
    }
    println!();
}