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 (Python):




class WeightedUnionFind:
    def __init__(self, n):
        self.n = n
        self.nodes = [i for i in range(n)]
        self.weights = [0 for _ in range(n)]
        self.size = [1 for _ in range(n)]

    def connected(self, i, j):
        wi, ri = self.root(i)
        wj, rj = self.root(j)
        return ri == rj

    def union(self, i, j, w):
        wi, ri = self.root(i)
        wj, rj = self.root(j)
        if ri == rj:
            return

        if self.size[ri] < self.size[rj]:
            self.nodes[ri] = rj
            self.weights[ri] = wj - wi + w
            self.size[rj] += self.size[ri]
        else:
            self.nodes[rj] = ri
            self.weights[rj] = wi - wj - w
            self.size[ri] += self.size[rj]

    def weight(self, i, j):
        wi, ri = self.root(i)
        wj, rj = self.root(j)
        if ri != rj:
            raise ValueError('{} and {} is not connected'.format(i, j))

        return wi - wj

    def root(self, i):
        r = self.nodes[i]
        w = self.weights[i]
        while r != self.nodes[r]:
            w += self.weights[r]
            r = self.nodes[r]
        return w, r


def run():
    n, q = [int(i) for i in input().split()]
    wuf = WeightedUnionFind(n)

    for _ in range(q):
        com, *args = input().split()
        if com == '0':
            wuf.union(*[int(i) for i in args])
        elif com == '1':
            x, y = [int(i) for i in args]
            if wuf.connected(x, y):
                print(wuf.weight(x, y))
            else:
                print('?')


if __name__ == '__main__':
    run()

Solution (Python):
MAX = 100003
ws = [0 for i in range(MAX)] 
par = [-1 for i in range(MAX*2)]


def weight(x):
    root(x)
    return ws[x]

def root(x):
    if par[x] < 0: return x
    p = root(par[x])
    ws[x] = ws[x] + ws[par[x]]
    par[x] = p
    return par[x]


def unite(y, x, z):
    z = z + weight(x)
    z = z - weight(y)
    x = root(x)
    y = root(y)
    if x == y: return 0
    if par[y] < par[x]:
        tmp = x
        x = y 
        y = tmp 
        z = -z
     
    par[x] = par[x] + par[y]
    par[y] = x
    ws[y] = z
    return 1 

def diff(x,y):
    if root(x) != root(y) :return 0
    ans = ws[x] - ws[y]
    return 1 ,ans


if __name__=='__main__':
   global ans
   N, Q =  (int(x) for x in  input().split())
   for q in range(Q):
        t, *cmd =  (int(x) for x in  input().split())
        if t:
            x, y = cmd
            z = diff(x, y)
            if z==False :print("?")
            else :print(z[1])
        else:
            x, y, z = cmd
            unite(x, y, z)

Solution (Python):
MAX = 100005
ws = [0 for i in range(MAX)] 
par = [-1 for i in range(MAX*2)]


def weight(x):
    root(x)
    return ws[x]

def root(x):
    if par[x] < 0: return x
    p = root(par[x])
    ws[x] = ws[x] + ws[par[x]]
    par[x] = p
    return par[x]


def unite(y, x, z):
    z = z + weight(x)
    z = z - weight(y)
    x = root(x)
    y = root(y)
    if x == y: return 0
    if par[y] < par[x]:
        tmp = x
        x = y 
        y = tmp 
        z = -z
     
    par[x] = par[x] + par[y]
    par[y] = x
    ws[y] = z
    return 1 

def diff(x,y):
    if root(x) != root(y) :return 0
    ans = ws[x] - ws[y]
    return 1 ,ans


if __name__=='__main__':
   global ans
   N, Q =  (int(x) for x in  input().split())
   for q in range(Q):
        t, *cmd =  (int(x) for x in  input().split())
        if t:
            x, y = cmd
            z = diff(x, y)
            if z==False :print("?")
            else :print(z[1])
        else:
            x, y, z = cmd
            unite(x, y, z)

Solution (Python):
[p, rank] = [[], []]
[n, q] = list(map(int, input().split()))
w = [0 for i in range(n)]

def findSet(x):
    global p
    if x != p[x]:
        pre_parent = p[x]
        p[x] = findSet(p[x])
        w[x] += w[pre_parent]
    return p[x]

def makeSet(x):
    global p, rank
    p.append(x)
    rank.append(0)


def link(x, y, z):
    global p, rank, w
    if rank[x] > rank[y]:
        p[y] = x
        w[y] = z
    else:
        p[x] = y
        w[x] = -z
        if rank[x] == rank[y]:
            rank[y] += 1

def relate(x, y, z):
    global w
    root_x = findSet(x)
    root_y = findSet(y)
    z += w[x]
    z -= w[y]
    link(root_x, root_y, z)

def same(x, y):
    if findSet(x) == findSet(y):
        return 1
    else:
        return 0   
   
def difference(x, y):
    if same(x, y) == 1:
        global w
        return w[y] - w[x]
    else:
        return "?"     

for i in range(n):
    makeSet(i)

for i in range(q):
    data = list(map(int, input().split()))
    if data[0] == 0:
        relate(data[1], data[2], data[3])
    else:
        print(difference(data[1], data[2]))

Solution (Python):
import sys
sys.setrecursionlimit(50000)

def findset(x,element,weight):
    if(x != element[x]):
        element[x],s = findset(element[x],element,weight)
        weight[x] += s
    return element[x],weight[x]

def union(x,y,element,weight,w):
    x,wx = findset(x,element,weight)
    y,wy = findset(y,element,weight)
    link(x,wx,y,wy,w,element)
def link(x,wx,y,wy,z,element):
    z = z+wy-wx

    element[x] = y
    weight[x] = z

n,q = map(int, input().split());

element = [i for i in range(n)]
weight = [0 for i in range(n)]

for i in range(q):
    inp = map(int, input().split());
    inp = list(inp)    
    if(inp[0] == 0):
        x,y,w = inp[1],inp[2],inp[3]
        union(x,y,element,weight,w)
    else:
        x,y = inp[1],inp[2]
        x,wx = findset(x,element,weight)
        y,wy = findset(y,element,weight)
        if(x == y):
            print(wx-wy)
        else:
            print('?')

Solution (Python):
import sys
sys.setrecursionlimit(50000)

def findset(x,element,weight):
    if(x != element[x]):
        element[x],s = findset(element[x],element,weight)
        weight[x] += s
    return element[x],weight[x]

def union(x,y,element,weight,w):
    x,wx = findset(x,element,weight)
    y,wy = findset(y,element,weight)
    link(x,wx,y,wy,w,element)
def link(x,wx,y,wy,z,element):
    z = z+wy-wx

    element[x] = y
    weight[x] = z

n,q = map(int, input().split());

element = [i for i in range(n)]
weight = [0 for i in range(n)]

for i in range(q):
    inp = map(int, input().split());
    inp = list(inp)    
    if(inp[0] == 0):
        x,y,w = inp[1],inp[2],inp[3]
        union(x,y,element,weight,w)
    else:
        x,y = inp[1],inp[2]
        x,wx = findset(x,element,weight)
        y,wy = findset(y,element,weight)
        if(x == y):
            print(wx-wy)
        else:
            print('?')

Solution (Python):
import sys
sys.setrecursionlimit(50000)

def findset(x,element,weight):
    if(x != element[x]):
        element[x],s = findset(element[x],element,weight)
        weight[x] += s
    return element[x],weight[x]

def union(x,y,element,weight,w):
    x,wx = findset(x,element,weight)
    y,wy = findset(y,element,weight)
    link(x,y,w+wy-wx,element,weight)

def link(x,y,z,element,weight):

    element[x] = y
    weight[x] = z

n,q = map(int, input().split());

element = [i for i in range(n)]
weight = [0 for i in range(n)]

for i in range(q):
    inp = map(int, input().split());
    inp = list(inp)    
    if(inp[0] == 0):
        x,y,w = inp[1],inp[2],inp[3]
        union(x,y,element,weight,w)
    else:
        x,y = inp[1],inp[2]
        x,wx = findset(x,element,weight)
        y,wy = findset(y,element,weight)
        if(x == y):
            print(wx-wy)
        else:
            print('?')

Solution (Python):

def union(x, y, t):
    x, t_x = findSet(x)
    y, t_y = findSet(y)
    link(x, t_x, y, t_y, t)


def link(x, d_x, y, d_y, t):
    
    
    
    if r[x] > r[y]:
        p[y] = x
        d[y] = d_x - d_y - t
        

    else:
        p[x] = y
        d[x] = d_y - d_x + t
        if r[x] == r[y]: r[y] = r[y] + 1
        


def findSet(x):
    if x != p[x]:
        p[x], t = findSet(p[x])
        d[x] += t
    return p[x], d[x]


def diff(x, y):
    x, d_x = findSet(x)
    y, d_y = findSet(y)
    if x == y:
        return d_x - d_y

    else:
        return '?'




if __name__ == '__main__':

    p, r, d = [], [], []

    n_set, n_quare = map(int, input().split())

    for i in range(n_set):
        p.append(i)
        r.append(0)
        d.append(0)


    for i in range(n_quare):
        l = input().split()

        if len(l) == 4:
            _, x, y, t = map(int, l)
            union(x, y, t)

        else:
            _, x, y = map(int, l)
            print(diff(x, y))

Solution (Python):

n, q = map(int, input().split())

p = [i for i in range(n)]
rank = [0 for i in range(n)]
diff_weight = [0 for i in range(n)]


def link(x, y, z):
 if rank[x] > rank[y]:
  p[y] = x
  diff_weight[y] = z
 else:
  p[x] = y
  diff_weight[x] = -z
  if rank[x] == rank[y]:
   rank[y] = rank[y] + 1

def findSet(x):
 if x != p[x]:
  parent = p[x]
  p[x] = findSet(p[x])
  diff_weight[x] += diff_weight[parent]
 return p[x]


def relate(x, y, z):
 rootx = findSet(x)
 rooty = findSet(y)
 z += diff_weight[x]
 z -= diff_weight[y]
 if rootx != rooty:
  link(rootx, rooty, z)


def same(x, y):
 x = findSet(x)
 y = findSet(y)

 if x == y:
  return 1
 else :
  return 0

def weight(x):
 findSet(x)
 return diff_weight[x]

def diff(x, y):
 if same(x, y) != 1:
  return '?'
 else :
  return diff_weight[y] - diff_weight[x]


output = []

for i in range(q):
 
 
 
 line = list(map(int, input().split()))

 if line[0] == 0:
  relate(line[1], line[2], line[3])

 else :
  output.append(diff(line[1],line[2]))
  


for ans in output:
 print(ans)

Solution (Python):

[p, rank] = [[], []]
[n, q] = list(map(int, input().split()))
w = [0 for i in range(n)]

def makeSet(x):
    global p, rank
    p.append(x)
    rank.append(0)

def findSet(x):
    global p
    if x != p[x]:
        pre_parent = p[x]
        p[x] = findSet(p[x])
        w[x] += w[pre_parent]
    return p[x]

def link(x, y, z):
    global p, rank, w
    if rank[x] > rank[y]:
        p[y] = x
        w[y] = z
    else:
        p[x] = y
        w[x] = -z
        if rank[x] == rank[y]:
            rank[y] += 1

def same(x, y):
    if findSet(x) == findSet(y):
        return 1
    else:
        return 0   

def relate(x, y, z):
    global w
    root_x = findSet(x)
    root_y = findSet(y)
    z += w[x]
    z -= w[y]
    link(root_x, root_y, z)
   
def diff(x, y):
    if same(x, y) == 1:
        global w
        return w[y] - w[x]
    else:
        return "?"     

for i in range(n):
    makeSet(i)

for i in range(q):
    data = list(map(int, input().split()))
    if data[0] == 0:
        relate(data[1], data[2], data[3])
    else:
        print(diff(data[1], data[2]))

Solution (Python):
idx_com = 0
idx_x = 1
idx_y = 2
idx_z = 3

n, nq = map(int, input().split())
parents = list(range(n))
ranks = [0] * n
weights = [0] * n

def find(x):
    if parents[x] == x:
        return x
    y = find(parents[x])
    weights[x] += weights[parents[x]]
    parents[x] = y
    return y

def unite(x, y, w):
    root_x = find(x)
    root_y = find(y)

    if ranks[root_x] < ranks[root_y]:
        parents[root_x] = root_y
        weights[root_x] = -w - weights[x] + weights[y]
    else:
        parents[root_y] = root_x
        weights[root_y] = +w - weights[y] + weights[x]
        if ranks[root_x] == ranks[root_y]:
            ranks[root_x] += 1

def same(x, y):
    return find(x) == find(y)

def diff(x, y):
    return weights[y] - weights[x]

for _ in range(nq):
    q = list(map(int, input().split()))
    if q[idx_com] == 0:
        unite(q[idx_x], q[idx_y], q[idx_z])
    else:
        if same(q[idx_x], q[idx_y]):
            print(diff(q[idx_x], q[idx_y]))
        else:
            print("?")

Solution (Python):



class WeightedUnionFindTree():
    def __init__(self, n):
        self.par = [i for i in range(n+1)]
        self.rank = [0] * (n+1)
        self.weight = [0] * (n+1)

    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            y = self.find(self.par[x])
            self.weight[x] += self.weight[self.par[x]]
            self.par[x] = y
            return y

    def unite(self, x, y, w):
        rx = self.find(x)
        ry = self.find(y)
        if self.rank[rx] < self.rank[ry]:
            self.par[rx] = ry
            self.weight[rx] = w - self.weight[x] + self.weight[y]
        else:
            self.par[ry] = rx
            self.weight[ry] = -w - self.weight[y] + self.weight[x]
            if self.rank[rx] == self.rank[ry]:
                self.rank[rx] += 1

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def diff(self, x, y):
        return self.weight[x] - self.weight[y]

n, q = [int(x) for x in input().split(' ')]
wuft = WeightedUnionFindTree(n-1)
for i in range(q):
    query = [int(x) for x in input().split(' ')]
    if query[0] == 0:
        x, y, z = query[1:]
        wuft.unite(x, y, z)
    elif query[0] == 1:
        x, y = query[1:]
        if wuft.same(x, y):
            print(wuft.diff(x,y))
        else:
            print('?')

Solution (Python):
par = [i for i in range(100)]
rank = [0 for i in range(100)]
weight_to_root = [0 for i in range(100)]

def find(x):
    if par[x] == x:
        return x
    else:
        root = find(par[x])
        weight_to_root[x] += weight_to_root[par[x]]
        par[x] = root
        return root

def is_same(x,y):
    return find(x) == find(y)

def union(x,y,w):
    a = find(x)
    b = find(y)
    if a==b:
        return False
    if rank[a] > rank[b]:
        par[b] = a
        weight_to_root[b] = -w - weight_to_root[y] + weight_to_root[x]
    elif rank[a] < rank[b]:
        par[a] = b
        weight_to_root[a] = w - weight_to_root[x] + weight_to_root[y]
    else:
        par[b] = a
        weight_to_root[b] = -w - weight_to_root[y] + weight_to_root[x]
        rank[a] += 1
    return True

def diff(x,y):
    return weight_to_root[x] - weight_to_root[y]


def main():
    global rank,par,weight_to_root
    n,q = [int(i) for i in input().split()]
    rank = [0 for i in range(n)]
    par = [i for i in range(n)]
    weight_to_root = [0 for i in range(n)]
    for i in range(q):
        s = [int(j) for j in input().split()]
        if s[0] == 0:
            union(s[1],s[2],s[3])
        else:
            if is_same(s[1],s[2]):
                print(diff(s[1],s[2]))
            else:
                print('?')

if __name__ == '__main__':
    main()

Solution (Python):
import sys
input = sys.stdin.readline

class WeightedUnionFind:
    def __init__(self, N):
        self.parent = list(range(N))
        self.rank = [0] * N
        self.weight = [0] * N

    def find(self, x):
        stack = [x]
        while self.parent[x] != x:
            x = self.parent[x]
            stack.append(x)
        r = stack[-1]
        while stack:
            x = stack.pop()
            self.weight[x] += self.weight[self.parent[x]]
            self.parent[x] = r
        return r

    def unite(self, x, y, w):
        rx = self.find(x)
        ry = self.find(y)
        w += self.weight[x] - self.weight[y]
        x = rx
        y = ry
        if x == y:
            return False

        if self.rank[x] < self.rank[y]:
            x, y = y, x
            w = -w
        if self.rank[x] == self.rank[y]:
            self.rank[x] += 1
        self.parent[y] = x
        self.weight[y] = w
        return True

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def diff(self, x, y):
        self.find(x)
        self.find(y)
        return self.weight[y] - self.weight[x]

n, q = map(int, input().split())
wuf = WeightedUnionFind(n)
for _ in range(q):
    t, *data = map(int, input().split())
    if t == 0:
        x, y, z = data
        wuf.unite(x, y, z)
    else:
        x, y = data
        if not wuf.same(x, y):
            print('?')
        else:
            print(wuf.diff(x, y))

Solution (Python):








import sys
sys.setrecursionlimit(1000000)
N,Q = map(int,sys.stdin.readline().split())
qs = tuple(tuple(map(int,sys.stdin.readline().rstrip().split())) for _ in range(Q)) 

parents = list(range(N))
diffs = [0]*N

def root(x):
    if parents[x]==x:
        return x
    else:
        pr = root(parents[x])
        diffs[x] += diffs[parents[x]]
        parents[x] = pr
        return pr

def weight(x):
    root(x)
    return diffs[x]

def diff(x,y):
    return weight(y)-weight(x)

def issame(x,y):
    return root(x) == root(y)


def merge(x,y,w):
    
    rx = root(x)
    ry = root(y)
    
    diff = weight(x)+(w-weight(y))
    if rx == ry:
        return False
    if rx < ry:
        rx,ry,diff = ry,rx,-diff
    diffs[ry] = diff
    parents[ry] = rx
    return True

for q in qs:
    if q[0]==0:
        x,y,z = q[1:]
        merge(x,y,z)
    else:
        x,y = q[1:]
        if root(x)==root(y):
            print(diff(x,y))
        else:
            print("?")

Solution (Python):



class WeightedUnionFind:
    """
    重み付きUnionFind

    """
    root_position = 0

    def __init__(self, size: int):
        self.size = size
        
        
        self.parent = [-1] * size
        self.weight = [WeightedUnionFind.root_position] * size

    def find(self, x: int) -> (int, int):
        """
        xを含む集合の代表とxの代表からの位置を求める
        """
        if self.parent[x] < 0:
            return x, self.weight[x]
        
        same_group_items = []
        y = x
        while self.parent[y] >= 0:
            same_group_items.append(y)
            y = self.parent[y]
        w = 0
        while same_group_items:
            child = same_group_items.pop()
            w += self.weight[child]
            self.weight[child] = w
            self.parent[child] = y
        return y, self.weight[x]

    def unite(self, x: int, y: int, weight: int) -> bool:
        """
        xを含む集合とyを含む集合を併合する
        `weight[x] + weight = weight[y]`になるように辺に重みをもたせる。
        xとyがすでに同じ集合に含まれている場合Falseを返す。
        """
        root_x, weight_x = self.find(x)
        root_y, weight_y = self.find(y)

        if root_x == root_y:
            return False

        if self.parent[root_x] >= self.parent[root_y]:
            self.parent[root_x] += self.parent[root_y]
            self.parent[root_y] = root_x
            self.weight[root_y] = weight_x + weight - weight_y
        else:
            self.parent[root_y] += self.parent[root_x]
            self.parent[root_x] = root_y
            self.weight[root_x] = weight_y - weight - weight_x

        return True


def solve():
    n, q = map(int, input().split())
    uf = WeightedUnionFind(n)
    for _ in range(q):
        query = list(map(int, input().split()))
        if query[0] == 0:
            _, x, y, z = query
            uf.unite(x, y, z)
        else:
            _, x, y = query
            root_x, pos_x = uf.find(x)
            root_y, pos_y = uf.find(y)
            if root_x == root_y:
                print(pos_y - pos_x)
            else:
                print('?')


if __name__ == "__main__":
    solve()

Solution (Python):
def root(x):
    if(par[x]==x):
        return x
    else:
        r=root(par[x])
        diff_weight[x]+=diff_weight[par[x]]
        par[x]=r
        return r

def weight(x):
    root(x)
    return diff_weight[x]

def diff(x,y):
    return weight(y)-weight(x)

def relate(a,b,w):
    w+=weight(a);w-=weight(b)
    a=root(a)
    b=root(b)
    if(a==b):
        return False
    if rank[a]<rank[b]:
        a,b=b,a
        w=-w
    if rank[a]==rank[b]:
        rank[b]+=1
        par[b]=a
    par[b]=a
    diff_weight[b]=w
    siz[a]+=siz[b]
    return True

def size(a):
    return siz[root(a)]
    
def same(a,b):
    return root(a)==root(b)
    
N,Q=map(int,input().split())
par=[i for i in range(N)]
siz=[1 for _ in range(N)]
rank=[0 for _ in range(N)]
diff_weight=[0 for _ in range(N)]
for i in range(Q):
    query=list(map(int,input().split()))
    if not query[0]:
        X,Y,W=query[1:]
        relate(X,Y,W)
    else:
        X,Y=query[1:]
        if same(X,Y):
            print(diff(X,Y))
        else:
            print('?')

Solution (Python):
import sys 
input = sys.stdin.readline


class UnionFindWeighted:
    """ポテンシャル付きUnionFind"""
    def __init__(self, n):
        self.parent = [-1] * n
        self.weight = [0] * n
        self.cnt = n
        self.INF = 10 ** 18
       
    def root(self, x):
        """頂点xの根を求める"""
        if self.parent[x] < 0:
            return x
        rt = self.root(self.parent[x])
        self.weight[x] += self.weight[self.parent[x]]
        self.parent[x] = rt
        return rt

    def merge(self, x, y, weight):
        """頂点xを含む集合と頂点y含む集合を結合する
        weight: 頂点yに対する頂点xのポテンシャル(頂点xの方がweight高い)
        """
        root_x = self.root(x)
        root_y = self.root(y)
        if root_x == root_y:
            return
        if self.parent[root_x] < self.parent[root_y]:
            self.parent[root_x] += self.parent[root_y]
            self.parent[root_y] = root_x
            self.weight[root_y] = -weight + self.weight[x] - self.weight[y]
        else:
            self.parent[root_y] += self.parent[root_x]
            self.parent[root_x] = root_y
            self.weight[root_x] = weight - self.weight[x] + self.weight[y]
        self.cnt -= 1

    def is_same(self, x, y):
        """頂点x, yが同じ集合に属するかどうかを返す"""
        return self.root(x) == self.root(y)

    def diff(self, x, y):
        """頂点yに対する頂点xのポテンシャルを求める
        ただし、頂点x,y間にポテンシャルが定義されていない場合は INF を返す
        """
        if not self.is_same(x, y):
            return self.INF
        return self.weight[x] - self.weight[y]

    def get_size(self, x):
        """頂点xを含む集合の要素数を返す"""
        return -self.parent[self.root(x)]

    def get_cnt(self):
        """集合の個数を返す"""
        return self.cnt


def solve():
    n, q = list(map(int, input().split()))
    query = [list(map(int, input().split())) for i in range(q)]
    INF = 10 ** 18
    ufw = UnionFindWeighted(n)

    for i in range(q):
        if query[i][0] == 0:
            
            _, x, y, weight = query[i]
            ufw.merge(x, y, weight)
        else:
            
            _, x, y = query[i]
            ans = ufw.diff(x, y)
            if ans == INF:
                print("?")
            else:
                print(ans)


if __name__ == "__main__":
    solve()

Solution (Python):
import math

class weightedUnionTree:
    def __init__(self,n):
        self.par = [i for i in range(n+1)]
        self.rank = [0] * (n+1)
        self.weight = [0] * (n+1)

    def find(self,x):
        if self.par[x] == x:
            return x
        else:
            y = self.find(self.par[x])
            self.weight[x] += self.weight[self.par[x]]
            self.par[x] = y
            return y

    def union(self,x, y, w):
        rx = self.find(x)
        ry = self.find(y)
        

        if self.rank[rx] < self.rank[ry]:
            self.par[rx] = ry
            self.weight[rx] = w - self.weight[x] + self.weight[y]

        else:
            self.par[ry] = rx
            self.weight[ry] = -w - self.weight[y] + self.weight[x]

            if self.rank[rx] == self.rank[ry]:
                self.rank[rx] += 1

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def diff(self, x, y):
        """
        print("diff: ",end="")
        print(self.weight[x],end=" ")
        print(self.weight[y],end=" ")
        
        """

        if(self.same(x, y)): 
            print(self.weight[x] - self.weight[y])
        else:
            print("?")


if __name__ == "__main__":
    n, q = (int(p) for p in input().split())
    tree = weightedUnionTree(n)
    
    
    for i in range(q):
        question, num = input().split(' ', 1)
        
        
        if(int(question) == 0):
            
            x, y, z = num.split(' ')
            tree.union(int(x), int(y), int(z))
        else:
            
            x, y = num.split(' ')
            tree.diff(int(x), int(y))

Solution (Python):
rank = []
p = []
w = []

def makeSet(x):
    p.append(x)
    rank.append(0)
    w.append(0)


def union(x, y):
    link(findSet(x), findSet(y))


def link(x, y):
    if rank[x] > rank[y]:
        p[y] = x

    else:
        p[x] = y
        if rank[x] == rank[y]:
            rank[y] = rank[y] + 1


def findSet(x):
    if p[x] == x:
        return x

    i = findSet(p[x])
    w[x] += w[p[x]]
    p[x] = i
    return i


def same(x, y):
    return findSet(x) == findSet(y)

def relate (x,y,z):
    i = findSet(x)
    j = findSet(y)

    if rank[i] < rank[j]:
        p[i] = j
        w[i] = z - w[x] + w[y]
    else:
        p[j] = i
        w[j] = -z - w[y] + w[x]
        if rank[i] == rank[j]:
            rank[i] += 1

n, q = map(int, input().split())
for i in range(n):
    makeSet(i)
for i in range(q):
    com, *cmd = map(int, input().split())
    if com == 0:
        relate(cmd[0], cmd[1],cmd[2])
    else:
        x, y = cmd
        if same(x, y):
            print(w[x] - w[y])
        else:
            print("?")

Solution (Python):
import sys
sys.setrecursionlimit(50000)

def findSet(x,element,weight):
    if(x != element[x]):
        element[x],s = findSet(element[x],element,weight)
        weight[x] += s

    return element[x],weight[x]

def union(x,y,element,weight,w):
    x,wx = findSet(x, element, weight)
    y,wy = findSet(y, element, weight)

    link(x,wx,y,wy,w,element)
    
def link(x,wx,y,wy,z,element):
    z = z + wy - wx

    element[x] = y
    weight[x] = z

n,q = map(int, input().split());

element = [i for i in range(n)]
weight = [0 for i in range(n)]

for i in range(q):
    inp = map(int, input().split());
    inp = list(inp)    

    if(inp[0] == 0):
        x,y,w = inp[1],inp[2],inp[3]
        union(x,y,element,weight,w)
    else:
        x,y = inp[1],inp[2]
        x,wx = findSet(x,element,weight)
        y,wy = findSet(y,element,weight)

        if(x == y):
            print(wx - wy)
        else:
            print('?')

Solution (Python):
class WeightedUnionFind():
    def __init__(self,n):
        self.n=n
        self.parents=[-1]*n
        self.differ=[0]*n

    def find(self,x):
        if self.parents[x]<0:
            return x
        else:
            r=self.find(self.parents[x])
            self.differ[x]+=self.differ[self.parents[x]]
            self.parents[x]=r
            return self.parents[x]

    def unite(self,x,y,w):
        xp=self.find(x)
        yp=self.find(y)
        w=w+self.differ[x]-self.differ[y]

        if xp!=yp:
            if self.parents[xp]>self.parents[yp]:
                xp,yp=yp,xp
                w=-w

            self.parents[xp]+=self.parents[yp]
            self.parents[yp]=xp
            self.differ[yp]=w

    def diff(self,x,y):
        xp=self.find(x)
        yp=self.find(y)
        if xp==yp:
            return True,self.differ[y]-self.differ[x]
        else:
            return False,0

n,q=map(int,input().split())
WUF=WeightedUnionFind(n)
for i in range(q):
    query=list(map(int,input().split()))
    if query[0]==0:
        WUF.unite(query[1],query[2],query[3])
    elif query[0]==1:
        judge,diff=WUF.diff(query[1],query[2])
        if judge:
            print(diff)
        else:
            print("?")

Solution (Python):
class WeightedUnionFindTree():
    '''ランク付きUnionFind木'''
    def __init__(self, n):
        ''' 初期化 '''
        self.par = list(range(n))
        self.rank = [0] * n 
        self.w = [0] * n 

    def root(self, x):
        ''' 木の根を求める '''
        if self.par[x] == x:
            return x

        root = self.root(self.par[x])
        self.w[x] += self.w[self.par[x]]
        self.par[x] = root
        return root
    def relate(self, x, y, weight=0):
        
        root_x, root_y = self.root(x), self.root(y)
        if root_x == root_y: return;
        
        if self.rank[root_x] < self.rank[root_y]:
            self.par[root_x] = root_y 
            self.w[root_x] = weight - self.w[x] + self.w[y]
        else:
            self.par[root_y] = root_x 
            self.w[root_y] = -weight + self.w[x] - self.w[y]
            if self.rank[root_x] == self.rank[root_y]:
                self.rank[root_x] += 1

    def same(self, x, y):
        
        return self.root(x) == self.root(y)

    def diff(self, x, y):
        if self.same(x, y):
            return self.w[x] - self.w[y]
        else:
            return "?"

def querying(queries, uft):
    for query in queries:
        if query[0] == 0:
            uft.relate(query[1], query[2], query[3])
        else:
            print(uft.diff(query[1], query[2]))

if __name__ == '__main__':
    
    n, q = map(int, input().split())
    queries = [list(map(int, input().split())) for i in range(q)]
    uft = WeightedUnionFindTree(n)
    querying(queries, uft)

Solution (Python):
import sys
readline = sys.stdin.buffer.readline

n,q= map(int,readline().split())


class WeightedUnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n+1)]
        self.rank = [0] * (n+1)
        
        self.weight = [0] * (n+1)

    
    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            y = self.find(self.par[x])
            
            self.weight[x] += self.weight[self.par[x]]
            self.par[x] = y
            return y

    
    def union(self, x, y, w):
        rx = self.find(x)
        ry = self.find(y)
        
        if self.rank[rx] < self.rank[ry]:
            self.par[rx] = ry
            self.weight[rx] = w - self.weight[x] + self.weight[y]
        
        else:
            self.par[ry] = rx
            self.weight[ry] = -w - self.weight[y] + self.weight[x]
            
            if self.rank[rx] == self.rank[ry]:
                self.rank[rx] += 1

    
    def same(self, x, y):
        return self.find(x) == self.find(y)

    
    def diff(self, x, y):
        return self.weight[x] - self.weight[y]

uf = WeightedUnionFind(n)

for i in range(q):
    s = readline().rstrip().decode('utf-8')
    if s[0] == "0":
        com,a,b,w = map(int,s.split())
    else:
        com,a,b = map(int,s.split())
    if com:
        if uf.same(a,b):
            print(uf.diff(a,b))
        else:
            print("?")
    else:
        uf.union(a,b,w)