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 C++14 (judge verdict: Accepted)

#include <bits/stdc++.h>
using namespace std;

typedef int64_t i64;

constexpr i64 llinf=4611686018427387903LL;

template <class T_>
class wdjset{
public:
    i64 n;
    i64 *par;
    i64 gr;
    T_ *w;
    void make(i64 N){
        n=gr=N;
        par=new i64[n]{};
        w=new T_[n]{};
        for(i64 i=0;i<n;i++) par[i]=1;
    }
    inline i64 find(i64 X){
        if(par[X]>0) return X;
        else{
            i64 r=find(-par[X]);
            w[X]+=w[-par[X]];
            return -(par[X]=-r);
        }
    }
    i64 unite(i64 X,i64 Y,T_ W){
        i64 px=find(X),py=find(Y);
        if(px==py) return 0;
        W+=w[X];
        W-=w[Y];
        if(par[px]<par[py]){
            i64 t=px;
            px=py;
            py=t;
            W=-W;
        }
        par[px]+=par[py];
        par[py]=-px;
        w[py]=W;
        gr--;
        return 1;
    }
    i64 same(i64 X,i64 Y){
        return (find(X)==find(Y));
    }
    T_ diff(i64 X,i64 Y){
        if(!same(X,Y)) return (T_)llinf;
        return w[Y]-w[X];
    }
    i64 size(i64 x){
        return par[find(x)];
    }
    void refr(void){
        delete[] par;
    }
};

int main(void){
    i64 n,q;
    scanf("%lli%lli",&n,&q);
    wdjset<i64> s;
    s.make(n);
    for(i64 i=0;i<q;i++){
        i64 t;
        scanf("%lli",&t);
        if(t==0){
            i64 x,y,z;
            scanf("%lli%lli%lli",&x,&y,&z);
            s.unite(x,y,z);
        }
        else{
            i64 x,y;
            scanf("%lli%lli",&x,&y);
            i64 d=s.diff(x,y);
            if(d==llinf) printf("?\n");
            else printf("%lli\n",d);
        }
    }
    return 0;
}