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



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

Submission status: Wrong Answer

Solution code:
# Disjoint Set: Union Find Trees
[p, rank] = [[], []]
[n, q] = list(map(int, input().split()))
w = [0 for i in range(n)]
path_c = [[] for i in range(n)]
path_c_len = [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]:
        p[x] = findSet(p[x])
    return p[x]

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

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

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

def relate(x, y, z):
    global w, path_c
    path_c[y].append((x, z))
    path_c_len[y] += 1
    #print(w)
    if w[y] == 0:
        w[y] = w[x] + z
    else:
        update(x, y, z)
    union(x, y)

def update(x, y, z):
    global w, path_c
    w[x] = w[y] - z
    for i in range(path_c_len[x]):
        update(path_c[x][i][0], x, path_c[x][i][1])


def diff(x, y):
    if same(x, y) == 1:
        global w
        return w[y] - w[x]
        #return abs(w[y] - w[x])
    else:
        return "?"     

'''
print(p)
print(rank)
print(w)
print("\n")
'''

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]))
    '''
    print("\n")
    print(p)
    print(rank)
    print(w)
    print("\n")
    '''

Submission status: Wrong Answer

Solution code:
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[y] += 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:
        print(diff(q[idx_x], q[idx_y]))

Submission status: Wrong Answer

Solution code:
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[y] += 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("?")

Submission status: Wrong Answer

Solution code:
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[y]]
    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("?")

Submission status: Wrong Answer

Solution code:
def main():
    n,q = [int(i) for i in input().split()]
    par = [ i for i in range(n)]
    diff_weight = [ 0 for i in range(n)]
    rank = [ 0 for i in range(n)]
    def diff(x,y):
        return weight(y)-weight(x)

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

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

    def merge(x,y,w):
        w += weight(x)
        w -= weight(y)
        x = root(x)
        y = root(y)
        if x == y:
            return False
        if rank[x]<rank[y]:
            tmp = x
            x = y
            y = tmp
            w = -w
        if rank[x] == rank[y]:
            rank[x] += 1
        par[y] = x
        diff_weight[y] = w
        return True

    for i in range(q):
        s = [int(j) for j in input().split()]
        if s[0] == 0:
            merge(s[1],s[2],s[3])
        else:
            if root(s[1]) == root(s[2]):
                print(diff(s[1],s[2]))
            else:
                print('?')

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(50000)
def main():
    n,q = [int(i) for i in input().split()]
    par = [ i for i in range(n)]
    diff_weight = [ 0 for i in range(n)]
    rank = [ 0 for i in range(n)]
    def diff(x,y):
        return weight(y)-weight(x)

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

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

    def merge(x,y,w):
        w += weight(x)
        w -= weight(y)
        x = root(x)
        y = root(y)
        if x == y:
            return False
        if rank[x]<rank[y]:
            tmp = x
            x = y
            y = tmp
            w = -w
        if rank[x] == rank[y]:
            rank[x] += 1
        par[y] = x
        diff_weight[y] = w
        return True

    for i in range(q):
        s = [int(j) for j in input().split()]
        if s[0] == 0:
            merge(s[1],s[2],s[3])
        else:
            if root(s[1]) == root(s[2]):
                print(diff(s[1],s[2]))
            else:
                print('?')

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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


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

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

def diff(x,y):
    a=find(x)
    b=find(y)
    if a!=b:
        return "?"
    return weight_to_root[x]-weight_to_root[y]

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

def main():
    global weight_to_root,par,rank
    n,q = [int(i) for i in input().split()]
    weight_to_root = [ 0 for i in range(n)]
    par = [ i for i in range(n)]
    rank = [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:
            print(diff(s[1],s[2]))

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:

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

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

    def union(self, i, j, w):
        ri = self.root(i)
        rj = self.root(j)
        if ri != rj:
            assert self.weights[ri] == 0
            assert self.weights[rj] == 0
            wi = self.weight(i, ri)
            wj = self.weight(j, rj)
            self.nodes[ri] = rj
            self.weights[ri] = wj - wi + w
        else:
            assert self.weight(i, ri) - self.weight(j, ri) == w

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

        return wi - wj

    def root(self, i):
        ri = self.nodes[i]
        while ri != self.nodes[ri]:
            ri = self.nodes[ri]
        return ri


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

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10000)

def simplefindset(x,element,resultPos=0):
    if(x != element[x]):
        resultPos = simplefindset(element[x],element,resultPos)
    else:
        resultPos = x
    return resultPos

def findset(x,element,weight,resultPos=0,sumW=0):
    if(x != element[x]):
        resultPos,sumW = findset(element[x],element,weight,resultPos,sumW)
    else:
        resultPos = x
    sumW += weight[x]
    return resultPos,sumW

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]
        if(simplefindset(x,element) == simplefindset(y,element)):
            x,wx = findset(x,element,weight)
            y,wy = findset(y,element,weight)
            print(wx-wy)
        else:
            print('?')

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10000)

def findset(x,element,weight,resultPos=0,sumW=0):
    if(x != element[x]):
        resultPos,sumW = findset(element[x],element,weight,resultPos,sumW)
        sumW += weight[x]
    else:
        resultPos = x
    return resultPos,sumW

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('?')

Submission status: Time Limit Exceeded

Solution code:
# Disjoint Set: Union Find Tree
[p, rank, d] = [[], [], []]
w = {}

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

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

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

def relate(x, y, z):
    global w
    w[(x, y)] = z
    union(x, y)

def cost(x, y, n, total):
    global w, d
    for i in range(n):
        if ((x, i) in w.keys()) == True and d[i] == 0:
            d[i] = 1
            if i == y:
                total += w[(x, i)]
                return total
            result = cost(i, y, n, total)
            if result != None:
                total = result + w[(x, i)]
                return total     

        if ((i, x) in w.keys()) == True and d[i] == 0:
            d[i] = 1
            if i == y:
                total -= w[(i, x)]
                return total
            result = cost(i, y, n, total)
            if result != None:
                total = result - w[(i, x)]
                return total

def diff(x, y, n):
    if same(x, y) == 1:
        global d
        total = 0
        d = [0 for i in range(n)]
        d[x] = 1
        return cost(x, y, n, total)
    else:
        return "?"     

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

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

[n, q] = list(map(int, input().split()))
for i in range(n):
    makeSet(i)
'''
print(p)
print(rank)
print(w)
print("\n")
'''

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], n))
    '''
    print("\n")
    print(p)
    print(rank)
    print(w)
    print("\n")
    '''

Submission status: Time Limit Exceeded

Solution code:
# Disjoint Set: Union Find Tree
[p, rank, d] = [[], [], []]
[n, q] = list(map(int, input().split()))
#time = 0

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

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

w = [[] for i in range(n)]

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

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

def relate(x, y, z):
    global w
    w[x].append((y, z))
    union(x, y)

def cost(x, y, n, total):
    global w, d, time
    #time += 1
    #if time > 5:
    #    return None
    for i in range(len(w[x])):
        if d[w[x][i][0]] == 0:
            #print(x, w[x][i][0])
            d[w[x][i][0]] = 1
            if y == w[x][i][0]:
                total += w[x][i][1]
                return total
            result = cost(w[x][i][0], y, n, total)
            if result != None:
                total = result + w[x][i][1]
                return total

    for i in range(n):
        for j in range(len(w[i])):
            if w[i][j][0] == x and d[i] == 0:
                #print(i, x)
                d[i] = 1
                if y == i:
                    total -= w[i][j][1]
                    return total
                result = cost(i, y, n, total)
                if result != None:
                    total = result - w[i][j][1]
                    return total

'''
        if ((x, i) in w.keys()) == True and d[i] == 0:
            d[i] = 1
            if i == y:
                total += w[(x, i)]
                return total
            result = cost(i, y, n, total)
            if result != None:
                total = result + w[(x, i)]
                return total     

        if ((i, x) in w.keys()) == True and d[i] == 0:
            d[i] = 1
            if i == y:
                total -= w[(i, x)]
                return total
            result = cost(i, y, n, total)
            if result != None:
                total = result - w[(i, x)]
                return total
                '''

def diff(x, y, n):
    if same(x, y) == 1:
        global d
        total = 0
        d = [0 for i in range(n)]
        d[x] = 1
        return cost(x, y, n, total)
    else:
        return "?"     

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

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

'''
print(p)
print(rank)
print(w)
print("\n")
'''

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], n))
    '''
    print("\n")
    print(p)
    print(rank)
    print(w)
    print("\n")
    '''

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# DSL_1_B: Weighted Union Find Trees


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

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
[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]))

Submission status: Accepted

Solution code:
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('?')

Submission status: Accepted

Solution code:
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('?')

Submission status: Accepted

Solution code:

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):
    #print('', 'x', 'y')
    #print('', x, y)
    #print('', d_x, d_y, t)
    if r[x] > r[y]:
        p[y] = x
        d[y] = d_x - d_y - t
        #print('', y, '->', p[y], '=', d[y], '\n')

    else:
        p[x] = y
        d[x] = d_y - d_x + t
        if r[x] == r[y]: r[y] = r[y] + 1
        #print('', x, '->', p[x], '=', d[x], '\n')


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))

Submission status: Accepted

Solution code:

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):
 #print(p)
 #print(rank)
 #print(diff_weight)
 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]))
  #print(diff(line[1],line[2]))


for ans in output:
 print(ans)

Submission status: Accepted

Solution code:
# Disjoint Set: Union Find Trees
[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]))

Submission status: Accepted

Solution code:
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("?")

Submission status: Accepted

Solution code:
#! python3
# weighted_union_find_tree.py

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('?')