Problem:


Score : 600 points

Problem Statement

There is a tree with N vertices numbered 1 to N.
The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively.
Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and different integers correspond to different colors.

Answer the following Q queries:

Query j (1 \leq j \leq Q): assuming that the length of every edge whose color is x_j is changed to y_j, find the distance between Vertex u_j and Vertex v_j. (The changes of the lengths of edges do not affect the subsequent queries.)

Constraints

2 \leq N \leq 10^5

1 \leq Q \leq 10^5

1 \leq a_i, b_i \leq N

1 \leq c_i \leq N-1

1 \leq d_i \leq 10^4

1 \leq x_j \leq N-1

1 \leq y_j \leq 10^4

1 \leq u_j < v_j \leq N

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
a_1 b_1 c_1 d_1
:
a_{N-1} b_{N-1} c_{N-1} d_{N-1}
x_1 y_1 u_1 v_1
:
x_Q y_Q u_Q v_Q

Output

Print Q lines. The j-th line (1 \leq j \leq Q) should contain the answer to Query j.

Sample Input 1

5 3
1 2 1 10
1 3 2 20
2 4 4 30
5 2 1 40
1 100 1 4
1 100 1 5
3 1000 3 4

Sample Output 1

130
200
60

The graph in this input is as follows:

Here the edges of Color 1 are shown as solid red lines, the edge of Color 2 is shown as a bold green line, and the edge of Color 4 is shown as a blue dashed line.

Query 1: Assuming that the length of every edge whose color is 1 is changed to 100, the distance between Vertex 1 and Vertex 4 is 100 + 30 = 130.

Query 2: Assuming that the length of every edge whose color is 1 is changed to 100, the distance between Vertex 1 and Vertex 5 is 100 + 100 = 200.

Query 3: Assuming that the length of every edge whose color is 3 is changed to 1000 (there is no such edge), the distance between Vertex 3 and Vertex 4 is 20 + 10 + 30 = 60. Note that the edges of Color 1 now have their original lengths.



Sample input:
5 3
1 2 1 10
1 3 2 20
2 4 4 30
5 2 1 40
1 100 1 4
1 100 1 5
3 1000 3 4


Sample output:
130
200
60

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys

#input = lambda: sys.stdin.readline()[:-1]
read = sys.stdin.read

class BinaryLiftingLCA:
    '''
    参考: https://tjkendev.github.io/procon-library/python/graph/lca-doubling.html
    '''
    def __init__(self, N):
        self.N = N
        self.G = [[] for _ in range(N)]
    
    def add_edge(self, a, b):
        self.G[a].append(b)
        self.G[b].append(a)
        
    def from_graph(self, G):
        self.G = G
        
    def build(self,root=0):
        from copy import deepcopy
        self.root = root
        self._bfs(root)
        self.maxdepth = max(self.d).bit_length()
        self.table = [self.prev]
        tmp1 = deepcopy(self.prev)
        for i in range(self.maxdepth):
            tmp2 = [0]*self.N
            for j in range(self.N):
                if tmp1[j] == -1: continue
                tmp2[j] = tmp1[tmp1[j]]
            self.table.append(tmp2)
            tmp1 = tmp2
            
    def lca(self,u, v):
        dd = self.d[v] - self.d[u]
        if dd < 0:
            u, v = v, u
            dd = -dd
        for k in range(self.maxdepth+1):
            if dd & 1: v = self.table[k][v]
            dd >>= 1
        if u == v: return u
        for i in range(self.maxdepth-1, -1, -1):
            pu = self.table[i][u]; pv = self.table[i][v]
            if pu != pv: u = pu; v = pv
        return self.table[self.root][u]
        
                
    def _bfs(self,s):
        from collections import deque
        seen = [0]*self.N
        self.d = [0]*self.N
        self.prev = [-1]*self.N
        todo = deque()
        seen[s]=1
        todo.append(s)
        while len(todo):
            a = todo.popleft()
            for b in self.G[a]:
                if seen[b] == 0:
                    seen[b] = 1
                    todo.append(b)
                    self.d[b] += self.d[a] + 1
                    self.prev[b] = a

def bfs(G,s):
    N = len(G)
    seen = [0]*N
    csum = [{} for _ in range(N)]
    cnum = [{} for _ in range(N)]
    d = [0]*N
    todo = deque()
    seen[s]=1
    todo.append(s)
    while todo:
      a = todo.popleft()
      for b in G[a].keys():
        if seen[b] == 0:
          seen[b] = 1
          todo.append(b)
          d_ = G[a][b][1]
          d[b] = d[a] + d_
          c_ = G[a][b][0]
          csum[b].update(csum[a])
          cnum[b].update(cnum[a])
          if csum[b].get(c_):
            csum[b][c_] += d_
            cnum[b][c_] += 1
          else:
            csum[b][c_] = d_
            cnum[b][c_] = 1
    return csum,cnum,d
  
def argmax(arr):
    return arr.index(max(arr))
  
def solve(env,x,y,u,v):
  lca,csum,cnum,d = env
  w = lca.lca(u,v)
  cs1,cn1 = ((csum[u][x],cnum[u][x]) if csum[u].get(x) else (0,0))
  cs2,cn2 = ((csum[v][x],cnum[v][x]) if csum[v].get(x) else (0,0))
  cs3,cn3 = ((csum[w][x],cnum[w][x]) if csum[w].get(x) else (0,0))
  diff1 = cn1*y - cs1
  diff2 = cn2*y - cs2
  diff3 = cn3*y - cs3
  return d[u]+diff1 + d[v]+diff2 - (d[w]+diff3)*2

def main():
  N,Q = map(int,input().split())
  abcd = [tuple(map(int,input().split())) for _ in range(N-1)]
  G = [{} for _ in range(N)]
  lca = BinaryLiftingLCA(N)
  for a,b,c,d in abcd:
    G[a-1][b-1] = G[b-1][a-1] = (c,d)
    lca.add_edge(a-1,b-1)

  #root = argmax([len(G[i]) for i in range(N)])
  lca.build(0)
  csum,cnum,d = bfs(G,0)
  ans = [0]*Q
  xyuv = [tuple(map(int,input().split())) for _ in range(Q)]
  #xyuv = tuple(map(int,read().split()))
  ans = [solve([lca,csum,cnum,d],x,y,u-1,v-1) for x,y,u,v in xyuv]
  print(*ans,sep='\n')
    
if __name__=="__main__":
  main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys

input = lambda: sys.stdin.readline()[:-1]
read = sys.stdin.read

class BinaryLiftingLCA:
    '''
    参考: https://tjkendev.github.io/procon-library/python/graph/lca-doubling.html
    '''
    def __init__(self, N):
        self.N = N
        self.G = [[] for _ in range(N)]
    
    def add_edge(self, a, b):
        self.G[a].append(b)
        self.G[b].append(a)
        
    def from_graph(self, G):
        self.G = G
        
    def build(self,root=0):
        from copy import deepcopy
        self.root = root
        self._bfs(root)
        self.maxdepth = max(self.d).bit_length()
        self.table = [self.prev]
        tmp1 = deepcopy(self.prev)
        for i in range(self.maxdepth):
            tmp2 = [0]*self.N
            for j in range(self.N):
                if tmp1[j] == -1: continue
                tmp2[j] = tmp1[tmp1[j]]
            self.table.append(tmp2)
            tmp1 = tmp2
            
    def lca(self,u, v):
        dd = self.d[v] - self.d[u]
        if dd < 0:
            u, v = v, u
            dd = -dd
        for k in range(self.maxdepth+1):
            if dd & 1: v = self.table[k][v]
            dd >>= 1
        if u == v: return u
        for i in range(self.maxdepth-1, -1, -1):
            pu = self.table[i][u]; pv = self.table[i][v]
            if pu != pv: u = pu; v = pv
        return self.table[self.root][u]
        
                
    def _bfs(self,s):
        from collections import deque
        seen = [0]*self.N
        self.d = [0]*self.N
        self.prev = [-1]*self.N
        todo = deque()
        seen[s]=1
        todo.append(s)
        while len(todo):
            a = todo.popleft()
            for b in self.G[a]:
                if seen[b] == 0:
                    seen[b] = 1
                    todo.append(b)
                    self.d[b] += self.d[a] + 1
                    self.prev[b] = a

def bfs(G,s):
    N = len(G)
    seen = [0]*N
    csum = [{} for _ in range(N)]
    cnum = [{} for _ in range(N)]
    d = [0]*N
    todo = deque()
    seen[s]=1
    todo.append(s)
    while todo:
      a = todo.popleft()
      for b in G[a].keys():
        if seen[b] == 0:
          seen[b] = 1
          todo.append(b)
          d_ = G[a][b][1]
          d[b] = d[a] + d_
          c_ = G[a][b][0]
          csum[b].update(csum[a])
          cnum[b].update(cnum[a])
          if csum[b].get(c_):
            csum[b][c_] += d_
            cnum[b][c_] += 1
          else:
            csum[b][c_] = d_
            cnum[b][c_] = 1
    return csum,cnum,d
  
def argmax(arr):
    return arr.index(max(arr))

def main():
  N,Q = map(int,input().split())
  abcd = [tuple(map(int,input().split())) for _ in range(N-1)]
  G = [{} for _ in range(N)]
  lca = BinaryLiftingLCA(N)
  for a,b,c,d in abcd:
    G[a-1][b-1] = (c,d)
    G[b-1][a-1] = (c,d)
    lca.add_edge(a-1,b-1)

  root = argmax([len(G[i]) for i in range(N)])
  lca.build(0)
  csum,cnum,d = bfs(G,0)
  ans = [0]*Q
  xyuv = tuple(map(int,read().split()))
  for i in range(len(xyuv)//4):
    x,y,u,v = xyuv[i*4:(i+1)*4]
    u,v = u-1,v-1
    w = lca.lca(u,v)
    cs1,cn1 = ((csum[u][x],cnum[u][x]) if csum[u].get(x) else (0,0))
    cs2,cn2 = ((csum[v][x],cnum[v][x]) if csum[v].get(x) else (0,0))
    cs3,cn3 = ((csum[w][x],cnum[w][x]) if csum[w].get(x) else (0,0))
    diff1 = cn1*y - cs1
    diff2 = cn2*y - cs2
    diff3 = cn3*y - cs3
    ans[i] = d[u]+diff1 + d[v]+diff2 - (d[w]+diff3)*2
  print(*ans,sep='\n')
    
if __name__=="__main__":
  main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from copy import deepcopy
import sys

input = lambda: sys.stdin.readline()[:-1]
read = sys.stdin.read

class BinaryLiftingLCA:
    '''
    参考: https://tjkendev.github.io/procon-library/python/graph/lca-doubling.html
    '''
    def __init__(self, N):
        self.N = N
        self.G = [[] for _ in range(N)]
    
    def add_edge(self, a, b):
        self.G[a].append(b)
        self.G[b].append(a)
        
    def from_graph(self, G):
        self.G = G
        
    def build(self,root=0):
        from copy import deepcopy
        self.root = root
        self._bfs(root)
        self.maxdepth = (self.N-1).bit_length()
        self.table = [self.prev]
        tmp1 = deepcopy(self.prev)
        for i in range(self.maxdepth):
            tmp2 = [0]*self.N
            for j in range(self.N):
                if tmp1[j] == -1: continue
                tmp2[j] = tmp1[tmp1[j]]
            self.table.append(tmp2)
            tmp1 = tmp2
            
    def lca(self,u, v):
        dd = self.d[v] - self.d[u]
        if dd < 0:
            u, v = v, u
            dd = -dd
        for k in range(self.maxdepth+1):
            if dd & 1: v = self.table[k][v]
            dd >>= 1
        if u == v: return u
        for i in range(self.maxdepth-1, -1, -1):
            pu = self.table[i][u]; pv = self.table[i][v]
            if pu != pv: u = pu; v = pv
        return self.table[self.root][u]
        
                
    def _bfs(self,s):
        from collections import deque
        seen = [0]*self.N
        self.d = [0]*self.N
        self.prev = [-1]*self.N
        todo = deque()
        seen[s]=1
        todo.append(s)
        while len(todo):
            a = todo.popleft()
            for b in self.G[a]:
                if seen[b] == 0:
                    seen[b] = 1
                    todo.append(b)
                    self.d[b] += self.d[a] + 1
                    self.prev[b] = a

def bfs(G,s):
    N = len(G)
    seen = [0]*N
    csum = [{} for _ in range(N)]
    cnum = [{} for _ in range(N)]
    d = [0]*N
    todo = deque()
    seen[s]=1
    todo.append(s)
    while todo:
      a = todo.popleft()
      for b in G[a].keys():
        if seen[b] == 0:
          seen[b] = 1
          todo.append(b)
          d_ = G[a][b][1]
          d[b] = d[a] + d_
          c_ = G[a][b][0]
          csum[b].update(csum[a])
          cnum[b].update(cnum[a])
          if csum[b].get(c_):
            csum[b][c_] += d_
            cnum[b][c_] += 1
          else:
            csum[b][c_] = d_
            cnum[b][c_] = 1
    return csum,cnum,d
  
def argmax(arr):
    return arr.index(max(arr))

def main():
  N,Q = map(int,input().split())
  abcd = [tuple(map(int,input().split())) for _ in range(N-1)]
  G = [{} for _ in range(N)]
  lca = BinaryLiftingLCA(N)
  for a,b,c,d in abcd:
    G[a-1][b-1] = (c,d)
    G[b-1][a-1] = (c,d)
    lca.add_edge(a-1,b-1)

  root = argmax([len(G[i]) for i in range(N)])
  lca.build(0)
  csum,cnum,d = bfs(G,0)
  ans = [0]*Q
  xyuv = tuple(map(int,read().split()))
  for i in range(len(xyuv)//4):
    x,y,u,v = xyuv[i*4:(i+1)*4]
    u,v = u-1,v-1
    w = lca.lca(u,v)
    cs1,cn1 = ((csum[u][x],cnum[u][x]) if csum[u].get(x) else (0,0))
    cs2,cn2 = ((csum[v][x],cnum[v][x]) if csum[v].get(x) else (0,0))
    cs3,cn3 = ((csum[w][x],cnum[w][x]) if csum[w].get(x) else (0,0))
    diff1 = cn1*y - cs1
    diff2 = cn2*y - cs2
    diff3 = cn3*y - cs3
    ans[i] = d[u]+diff1 + d[v]+diff2 - (d[w]+diff3)*2
  print(*ans,sep='\n')
    
if __name__=="__main__":
  main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from copy import deepcopy
import sys

input = lambda: sys.stdin.readline()[:-1]
read = sys.stdin.read

class BinaryLiftingLCA:
    '''
    参考: https://tjkendev.github.io/procon-library/python/graph/lca-doubling.html
    '''
    def __init__(self, N):
        self.N = N
        self.G = [[] for _ in range(N)]
    
    def add_edge(self, a, b):
        self.G[a].append(b)
        self.G[b].append(a)
        
    def from_graph(self, G):
        self.G = G
        
    def build(self,root=0):
        from copy import deepcopy
        self.root = root
        self._bfs(root)
        self.maxdepth = (self.N-1).bit_length()
        self.table = [self.prev]
        tmp1 = deepcopy(self.prev)
        for i in range(self.maxdepth):
            tmp2 = [0]*self.N
            for j in range(self.N):
                if tmp1[j] == -1: continue
                tmp2[j] = tmp1[tmp1[j]]
            self.table.append(tmp2)
            tmp1 = tmp2
            
    def lca(self,u, v):
        dd = self.d[v] - self.d[u]
        if dd < 0:
            u, v = v, u
            dd = -dd
        for k in range(self.maxdepth+1):
            if dd & 1: v = self.table[k][v]
            dd >>= 1
        if u == v: return u
        for i in range(self.maxdepth-1, -1, -1):
            pu = self.table[i][u]; pv = self.table[i][v]
            if pu != pv: u = pu; v = pv
        return self.table[self.root][u]
        
                
    def _bfs(self,s):
        from collections import deque
        seen = [0]*self.N
        self.d = [0]*self.N
        self.prev = [-1]*self.N
        todo = deque()
        seen[s]=1
        todo.append(s)
        while len(todo):
            a = todo.popleft()
            for b in self.G[a]:
                if seen[b] == 0:
                    seen[b] = 1
                    todo.append(b)
                    self.d[b] += self.d[a] + 1
                    self.prev[b] = a

def bfs(G,s):
    N = len(G)
    seen = [0]*N
    csum = [{} for _ in range(N)]
    cnum = [{} for _ in range(N)]
    d = [0]*N
    todo = deque()
    seen[s]=1
    todo.append(s)
    while todo:
      a = todo.popleft()
      for b in G[a].keys():
        if seen[b] == 0:
          seen[b] = 1
          todo.append(b)
          d_ = G[a][b][1]
          d[b] = d[a] + d_
          c_ = G[a][b][0]
          csum[b] = deepcopy(csum[a])
          cnum[b] = deepcopy(cnum[a])
          if csum[b].get(c_):
            csum[b][c_] += d_
            cnum[b][c_] += 1
          else:
            csum[b][c_] = d_
            cnum[b][c_] = 1
    return csum,cnum,d
  
def argmax(arr):
    return arr.index(max(arr))

def main():
  N,Q = map(int,input().split())
  abcd = [tuple(map(int,input().split())) for _ in range(N-1)]
  G = [{} for _ in range(N)]
  lca = BinaryLiftingLCA(N)
  for a,b,c,d in abcd:
    G[a-1][b-1] = (c,d)
    G[b-1][a-1] = (c,d)
    lca.add_edge(a-1,b-1)

  root = argmax([len(G[i]) for i in range(N)])
  lca.build(0)
  csum,cnum,d = bfs(G,0)
  ans = [0]*Q
  xyuv = tuple(map(int,read().split()))
  for i in range(len(xyuv)//4):
    x,y,u,v = xyuv[i*4:(i+1)*4]
    u,v = u-1,v-1
    w = lca.lca(u,v)
    cs1,cn1 = ((csum[u][x],cnum[u][x]) if csum[u].get(x) else (0,0))
    cs2,cn2 = ((csum[v][x],cnum[v][x]) if csum[v].get(x) else (0,0))
    cs3,cn3 = ((csum[w][x],cnum[w][x]) if csum[w].get(x) else (0,0))
    diff1 = cn1*y - cs1
    diff2 = cn2*y - cs2
    diff3 = cn3*y - cs3
    ans[i] = d[u]+diff1 - (d[w]+diff3) + d[v]+diff2 - (d[w]+diff3)
  print(*ans,sep='\n')
    
if __name__=="__main__":
  main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from copy import deepcopy
import sys

input = lambda: sys.stdin.readline()[:-1]
read = sys.stdin.read

class EulerTour:
    def __init__(self, N):
        self.N = N
        self.G = [[] for _ in range(N)]
    
    def add_edge(self, a, b):
        self.G[a].append(b)
        self.G[b].append(a)
    
    def from_graph(self, G, copy=False):
        if copy: self.G = deepcopy(G)
        else: self.G = G
            
    def build(self, root=0, lca=True):
        self.root = root
        self._dfs(root)
        self.In = [0]*self.N
        self.Out = [0]*self.N
        for i, v in enumerate(self.node_list):
            if self.In[v] == 0: self.In[v] = i
            self.Out[v] = i
        if lca:
            self.seg = SegTree(len(self.node_list))
            self.seg.build([self.d[self.node_list[i]] for i in range(len(self.node_list))])
    
    def lca(self, a, b):
        if self.root in (a,b):
            return self.root
        a_out, b_in = self.Out[a], self.In[b]
        if a_out > b_in:
            a_out, b_in = self.Out[b], self.In[a]
        if a_out > b_in:
            a_out, b_in = self.Out[b], self.Out[a]
        if a_out > b_in:
            a_out, b_in = self.Out[a], self.Out[b]
        idx = self.seg.find(a_out, b_in+1)
        return self.node_list[idx]
            
    def _dfs(self, root=0):
        self.idx2edge = {}
        self.edge2idx = {}
        self.node_list = []
        self.edge_list = []
        seen = [0]*len(self.G)
        prev = [0]*len(self.G)
        self.d =[-1]*len(self.G)
        todo = [~root, root]
        count = 0
        while todo:
            a = todo.pop()
            if a >= 0:
                seen[a] = 1
                self.d[a] = self.d[prev[a]] + 1
                edge = (prev[a], a)
                self.idx2edge[count] = edge
                self.edge2idx[edge] = count
                self.edge_list.append(count)
                self.node_list.append(a)
                count += 1
                for b in reversed(self.G[a]):
                    if seen[b]: continue
                    todo.append(~b)
                    todo.append(b)
                    prev[b] = a
            else: 
                edge = (prev[~a], ~a)
                idx = self.edge2idx[edge]
                self.edge_list.append(-idx)
                if ~a != root: self.node_list.append(prev[~a])
                    
class SegTree:
    """ segment tree with point modification and range product. """
    # # https://yukicoder.me/submissions/452850
    def __init__(self, N, data_f = min, data_unit=1<<30):
        self.N = N
        self.data_f = data_f
        self.data_unit = data_unit
        self.data = [self.data_unit] * (N + N)

    def build(self, raw_data):
        data = self.data
        f = self.data_f
        N = self.N
        data[N:] = raw_data[:]
        for i in range(N - 1, 0, -1):
            data[i] = f(data[i << 1], data[i << 1 | 1])

    def set_val(self, i, x):
        data = self.data
        f = self.data_f
        i += self.N
        data[i] = x
        while i > 1:
            data[i >> 1] = f(data[i], data[i ^ 1])
            i >>= 1

    def fold(self, L, R):
        """ compute for [L, R) """
        vL = vR = self.data_unit
        data = self.data
        f = self.data_f
        L += self.N
        R += self.N
        while L < R:
            if L & 1:
                vL = f(vL, data[L])
                L += 1
            if R & 1:
                R -= 1
                vR = f(data[R], vR)
            L >>= 1
            R >>= 1
        return f(vL, vR)
    
    def find(self, L, R):
        x = self.fold(L,R)
        while R-L>1:
            M = (R+L)//2
            if self.fold(L,M)==x: R = M
            else: L = M
        return L

def bfs(G,s):
    N = len(G)
    seen = [0]*N
    csum = [{} for _ in range(N)]
    cnum = [{} for _ in range(N)]
    d = [0]*N
    todo = deque()
    seen[s]=1
    todo.append(s)
    while todo:
      a = todo.popleft()
      for b in G[a].keys():
        if seen[b] == 0:
          seen[b] = 1
          todo.append(b)
          d_ = G[a][b][1]
          d[b] = d[a] + d_
          c_ = G[a][b][0]
          csum[b] = deepcopy(csum[a])
          cnum[b] = deepcopy(cnum[a])
          if csum[b].get(c_):
            csum[b][c_] += d_
            cnum[b][c_] += 1
          else:
            csum[b][c_] = d_
            cnum[b][c_] = 1
    return csum,cnum,d
  
def argmax(arr):
    return arr.index(max(arr))

def main():
  N,Q = map(int,input().split())
  abcd = [tuple(map(int,input().split())) for _ in range(N-1)]
  G = [{} for _ in range(N)]
  et = EulerTour(N)
  for a,b,c,d in abcd:
    G[a-1][b-1] = (c,d)
    G[b-1][a-1] = (c,d)
    et.add_edge(a-1,b-1)

  root = argmax([len(G[i]) for i in range(N)])
  et.build(root)
  csum,cnum,d = bfs(G,root)
  ans = [0]*Q
  xyuv = tuple(map(int,read().split()))
  for i in range(len(xyuv)//4):
    x,y,u,v = xyuv[i*4:(i+1)*4]
    u,v = u-1,v-1
    w = et.lca(u,v)
    diff1 = cnum[u][x]*y-csum[u][x] if csum[u].get(x) else 0
    diff2 = cnum[v][x]*y-csum[v][x] if csum[v].get(x) else 0
    diff3 = cnum[w][x]*y-csum[w][x] if csum[w].get(x) else 0
    ans[i] = d[u]+diff1 - (d[w]+diff3) + d[v]+diff2 - (d[w]+diff3)
  print(*ans)
    
if __name__=="__main__":
  main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from copy import deepcopy
import sys

input = lambda: sys.stdin.readline()[:-1]
read = sys.stdin.read

class EulerTour:
    def __init__(self, N):
        self.N = N
        self.G = [[] for _ in range(N)]
    
    def add_edge(self, a, b):
        self.G[a].append(b)
        self.G[b].append(a)
    
    def from_graph(self, G, copy=False):
        if copy: self.G = deepcopy(G)
        else: self.G = G
            
    def build(self, root=0, lca=True):
        self.root = root
        self._dfs(root)
        self.In = [0]*self.N
        self.Out = [0]*self.N
        for i, v in enumerate(self.node_list):
            if self.In[v] == 0: self.In[v] = i
            self.Out[v] = i
        if lca:
            self.seg = SegTree(len(self.node_list))
            self.seg.build([self.d[self.node_list[i]] for i in range(len(self.node_list))])
    
    def lca(self, a, b):
        if self.root in (a,b):
            return self.root
        a_out, b_in = self.Out[a], self.In[b]
        if a_out > b_in:
            a_out, b_in = self.Out[b], self.In[a]
        if a_out > b_in:
            a_out, b_in = self.Out[b], self.Out[a]
        if a_out > b_in:
            a_out, b_in = self.Out[a], self.Out[b]
        idx = self.seg.find(a_out, b_in+1)
        return self.node_list[idx]
            
    def _dfs(self, root=0):
        self.idx2edge = {}
        self.edge2idx = {}
        self.node_list = []
        self.edge_list = []
        seen = [0]*len(self.G)
        prev = [0]*len(self.G)
        self.d =[-1]*len(self.G)
        todo = [~root, root]
        count = 0
        while todo:
            a = todo.pop()
            if a >= 0:
                seen[a] = 1
                self.d[a] = self.d[prev[a]] + 1
                edge = (prev[a], a)
                self.idx2edge[count] = edge
                self.edge2idx[edge] = count
                self.edge_list.append(count)
                self.node_list.append(a)
                count += 1
                for b in reversed(self.G[a]):
                    if seen[b]: continue
                    todo.append(~b)
                    todo.append(b)
                    prev[b] = a
            else: 
                edge = (prev[~a], ~a)
                idx = self.edge2idx[edge]
                self.edge_list.append(-idx)
                if ~a != root: self.node_list.append(prev[~a])
                    
class SegTree:
    """ segment tree with point modification and range product. """
    # # https://yukicoder.me/submissions/452850
    def __init__(self, N, data_f = min, data_unit=1<<30):
        self.N = N
        self.data_f = data_f
        self.data_unit = data_unit
        self.data = [self.data_unit] * (N + N)

    def build(self, raw_data):
        data = self.data
        f = self.data_f
        N = self.N
        data[N:] = raw_data[:]
        for i in range(N - 1, 0, -1):
            data[i] = f(data[i << 1], data[i << 1 | 1])

    def set_val(self, i, x):
        data = self.data
        f = self.data_f
        i += self.N
        data[i] = x
        while i > 1:
            data[i >> 1] = f(data[i], data[i ^ 1])
            i >>= 1

    def fold(self, L, R):
        """ compute for [L, R) """
        vL = vR = self.data_unit
        data = self.data
        f = self.data_f
        L += self.N
        R += self.N
        while L < R:
            if L & 1:
                vL = f(vL, data[L])
                L += 1
            if R & 1:
                R -= 1
                vR = f(data[R], vR)
            L >>= 1
            R >>= 1
        return f(vL, vR)
    
    def find(self, L, R):
        x = self.fold(L,R)
        while R-L>1:
            M = (R+L)//2
            if self.fold(L,M)==x: R = M
            else: L = M
        return L

def bfs(G,s):
    N = len(G)
    seen = [0]*N
    csum = [{} for _ in range(N)]
    cnum = [{} for _ in range(N)]
    d = [0]*N
    todo = deque()
    seen[s]=1
    todo.append(s)
    while todo:
      a = todo.popleft()
      for b in G[a].keys():
        if seen[b] == 0:
          seen[b] = 1
          todo.append(b)
          d_ = G[a][b][1]
          d[b] = d[a] + d_
          c_ = G[a][b][0]
          csum[b] = deepcopy(csum[a])
          cnum[b] = deepcopy(cnum[a])
          if csum[b].get(c_):
            csum[b][c_] += d_
            cnum[b][c_] += 1
          else:
            csum[b][c_] = d_
            cnum[b][c_] = 1
    return csum,cnum,d
  
def argmax(arr):
    return arr.index(max(arr))

def main():
  N,Q = map(int,input().split())
  abcd = [tuple(map(int,input().split())) for _ in range(N-1)]
  G = [{} for _ in range(N)]
  et = EulerTour(N)
  for a,b,c,d in abcd:
    G[a-1][b-1] = (c,d)
    G[b-1][a-1] = (c,d)
    et.add_edge(a-1,b-1)

  root = argmax([len(G[i]) for i in range(N)])
  et.build(root)
  csum,cnum,d = bfs(G,root)
  ans = [0]*Q
  xyuv = tuple(map(int,read().split()))
  for i in range(len(xyuv)//4):
    x,y,u,v = xyuv[i*4:(i+1)*4]
    u,v = u-1,v-1
    w = et.lca(u,v)
    diff1 = cnum[u][x]*y-csum[u][x] if csum[u].get(x) else 0
    diff2 = cnum[v][x]*y-csum[v][x] if csum[v].get(x) else 0
    diff3 = cnum[w][x]*y-csum[w][x] if csum[w].get(x) else 0
    ans[i] = str(d[u]+diff1 - (d[w]+diff3) + d[v]+diff2 - (d[w]+diff3))
  print('\n'.join(ans))
    
if __name__=="__main__":
  main()