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

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

Submission status: Time Limit Exceeded

Solution code:
from copy import deepcopy
from collections import deque
import sys
sys.setrecursionlimit(10**8)

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

  # https://tjkendev.github.io/procon-library/python/graph/lca-dst.html
  S = []
  F = [0]*N
  depth = [0]*N
  seen = [0]*N
  def dfs(v, d):
      F[v] = len(S)
      depth[v] = d
      seen[v] = 1
      S.append(v)
      for w in G[v].keys():
          if seen[w]:continue
          dfs(w, d+1)
          S.append(v)
  dfs(0, 0)

  # Disjoint Sparse Tableの構築
  INF = (N, None)

  LV = (2*N-1).bit_length()
  N0 = 2**LV
  table = [[None]*N0 for i in range(LV)]

  S0 = [INF]*N0
  for i, v in enumerate(S):
      S0[i] = (depth[v], v)

  sz = N0; hf = N0 >> 1
  for k in range(LV):
      table_k = table[k]
      for i in range(hf, N0, sz):
          table_k[i-1] = r = S0[i-1]
          for j in range(i-2, i-hf-1, -1):
              table_k[j] = r = min(S0[j], r)

          table_k[i] = r = S0[i]
          for j in range(i+1, i+hf):
              table_k[j] = r = min(S0[j], r)
      sz >>= 1; hf >>= 1

  # LCAの計算
  def query(u, v):
      if u == v:
          return u
      fu = F[u]; fv = F[v]
      if fu > fv:
          fu, fv = fv, fu

      k2 = (fu ^ fv).bit_length()
      table_l = table[LV - k2]
      ans = table_l[fu]
      if fv & ((1 << k2) - 1):
          ans = min(ans, table_l[fv])
      return ans[1]

  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

  root = 0
  csum,cnum,d = bfs(G,root)
  ans = [0]*Q
  xyuv = [tuple(map(int,input().split())) for _ in range(Q)]
  for i,(x,y,u,v) in enumerate(xyuv):
    u,v = u-1,v-1
    w = query(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 copy import deepcopy
from collections import deque
import sys
sys.setrecursionlimit(10**8)

N,Q=map(int,input().split())
G=[{} for _ in range(N)]
for i in range(N-1):
  a,b,c,d = map(int,input().split())
  G[a-1][b-1] = (c,d)
  G[b-1][a-1] = (c,d)
  
# https://tjkendev.github.io/procon-library/python/graph/lca-dst.html
S = []
F = [0]*N
depth = [0]*N
seen = [0]*N
def dfs(v, d):
    F[v] = len(S)
    depth[v] = d
    seen[v] = 1
    S.append(v)
    for w in G[v].keys():
        if seen[w]:continue
        dfs(w, d+1)
        S.append(v)
dfs(0, 0)

# Disjoint Sparse Tableの構築
INF = (N, None)

LV = (2*N-1).bit_length()
N0 = 2**LV
table = [[None]*N0 for i in range(LV)]

S0 = [INF]*N0
for i, v in enumerate(S):
    S0[i] = (depth[v], v)

sz = N0; hf = N0 >> 1
for k in range(LV):
    table_k = table[k]
    for i in range(hf, N0, sz):
        table_k[i-1] = r = S0[i-1]
        for j in range(i-2, i-hf-1, -1):
            table_k[j] = r = min(S0[j], r)

        table_k[i] = r = S0[i]
        for j in range(i+1, i+hf):
            table_k[j] = r = min(S0[j], r)
    sz >>= 1; hf >>= 1

# LCAの計算
def query(u, v):
    if u == v:
        return u
    fu = F[u]; fv = F[v]
    if fu > fv:
        fu, fv = fv, fu

    k2 = (fu ^ fv).bit_length()
    table_l = table[LV - k2]
    ans = table_l[fu]
    if fv & ((1 << k2) - 1):
        ans = min(ans, table_l[fv])
    return ans[1]
  
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
  
root = 0
csum,cnum,d = bfs(G,root)
ans = [0]*Q
xyuv = [tuple(map(int,input().split())) for _ in range(Q)]
for i,(x,y,u,v) in enumerate(xyuv):
  u,v = u-1,v-1
  w = query(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')

Submission status: Time Limit Exceeded

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

sys.setrecursionlimit(10**8)

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

  MAX,root=0,-1
  for i in range(N):
    if len(G[i]) > MAX:
      MAX = len(G[i])
      root = i

  et.build(root)
  csum,cnum,d = bfs(G,root)
  ans = [0]*Q
  xyuv = [tuple(map(int,input().split())) for _ in range(Q)]
  for i,(x,y,u,v) in enumerate(xyuv):
    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()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from copy import deepcopy

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

  MAX,root=0,-1
  for i in range(N):
    if len(G[i]) > MAX:
      MAX = len(G[i])
      root = i

  et.build(root)
  csum,cnum,d = bfs(G,root)
  ans = [0]*Q
  xyuv = [tuple(map(int,input().split())) for _ in range(Q)]
  for i,(x,y,u,v) in enumerate(xyuv):
    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()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from copy import deepcopy

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 main():
  N,Q = map(int,input().split())
  G = [{} for _ in range(N)]
  et = EulerTour(N)
  for i in range(N-1):
    a,b,c,d = map(int,input().split())
    a,b = a-1,b-1
    G[a][b] = (c,d)
    G[b][a] = (c,d)
    et.add_edge(a,b)

  MAX,root=0,-1
  for i in range(N):
    if len(G[i]) > MAX:
      MAX = len(G[i])
      root = i

  et.build(root)
  csum,cnum,d = bfs(G,root)
  ans = [0]*Q
  for i in range(Q):
    x,y,u,v = map(int,input().split())
    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()