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
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)
          c_,d_ = G[a][b]
          d[b] = d[a] + d_
          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)
    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)
    
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):
        self.data[self.N:] = raw_data[:]
        for i in range(self.N - 1, 0, -1):
            self.data[i] = self.data_f(self.data[i << 1], self.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
        L += self.N
        R += self.N
        while L < R:
            if L & 1:
                vL = f = self.data_f(vL, self.data[L])
                L += 1
            if R & 1:
                R -= 1
                vR = f = self.data_f(self.data[R], vR)
            L >>= 1
            R >>= 1
        return self.data_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)
          c_, d_ = G[a][b]
          d[b] = d[a] + d_
          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)
    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)
    
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):
        self.data[self.N:] = raw_data[:]
        for i in range(self.N - 1, 0, -1):
            self.data[i] = self.data_f(self.data[i << 1], self.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
        L += self.N
        R += self.N
        while L < R:
            if L % 2:
                vL = f = self.data_f(vL, self.data[L])
                L += 1
            if R % 2:
                R -= 1
                vR = f = self.data_f(self.data[R], vR)
            L >>= 1
            R >>= 1
        return self.data_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)
          c_, d_ = G[a][b]
          d[b] = d[a] + d_
          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)
    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)
    
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

# https://nagiss.hateblo.jp/entry/2019/07/01/185421
class LCA:  # 最近共通祖先
    def __init__(self, E, root):
        import sys
        sys.setrecursionlimit(500000)
        self.root = root
        self.E = E  # V<V>
        self.n = len(E)  # 頂点数
        self.logn = 1  # n < 1<<logn  ぴったりはだめ
        while self.n >= (1<<self.logn):
            self.logn += 1

        # parent[n][v] = ノード v から 1<<n 個親をたどったノード
        self.parent = [[-1]*self.n for _ in range(self.logn)]

        self.depth = [0] * self.n
        self.dfs(root, -1, 0)
        for k in range(self.logn-1):
            for v in range(self.n):
                p_ = self.parent[k][v]
                if p_ >= 0:
                    self.parent[k+1][v] = self.parent[k][p_]

    def dfs(self, v, p, dep):
        # ノード番号、親のノード番号、深さ
        self.parent[0][v] = p
        self.depth[v] = dep
        for e in self.E[v].keys():
            if e != p:
                self.dfs(e, v, dep+1)

    def get(self, u, v):
        if self.depth[u] > self.depth[v]:
            u, v = v, u  # self.depth[u] <= self.depth[v]
        dep_diff = self.depth[v]-self.depth[u]
        for k in range(self.logn):
            if dep_diff >> k & 1:
                v = self.parent[k][v]
        if u==v:
            return u
        for k in range(self.logn-1, -1, -1):
            if self.parent[k][u] != self.parent[k][v]:
                u = self.parent[k][u]
                v = self.parent[k][v]
        return self.parent[0][u]

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)]
  for a,b,c,d in abcd:
    G[a-1][b-1] = (c,d)
    G[b-1][a-1] = (c,d)

  root = argmax([len(G[i]) for i in range(N)])
  lca = LCA(G,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 = lca.get(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)
    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()