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:
# ここまでやった
# おそらくこの方針でこれ以上は無理。sparse tableにしてもそんなに変わらない気がする。
# クエリを先読みしてオイラーツアーを使う必要あり。

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

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

Submission status: Time Limit Exceeded

Solution code:
# ここまでやった
# おそらくこの方針でこれ以上は無理。sparse tableにしてもそんなに変わらない気がする。
# クエリを先読みしてオイラーツアーを使う必要あり。

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] = 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
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():
  
  def solve(x,y,u,v):
    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
    return d[u]+diff1 + d[v]+diff2 - (d[w]+diff3)*2
    
  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)
  xyuv = tuple(map(int,read().split()))
  print(*[solve(*xyuv[i*4:(i+1)*4]) for i in range(len(xyuv)//4)],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].keys():
                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] = G[b-1][a-1] = (c,d)
    #lca.add_edge(a-1,b-1)

  lca.from_graph(G)
  #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
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,asked):
    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 c_ not in asked: continue
          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] = G[b-1][a-1] = (c,d)
    lca.add_edge(a-1,b-1)

  #root = argmax([len(G[i]) for i in range(N)])
  xyuv = tuple(map(int,read().split()))
  asked = set([xyuv[i*4:(i+1)*4][0] for i in range(len(xyuv)//4)])
  lca.build(0)
  csum,cnum,d = bfs(G,0,asked)
  ans = [0]*Q
  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
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 from_graph2(self, G2):
        self.G2 = G2
        
    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
                    del self.G2[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] = G[b-1][a-1] = (c,d)
    lca.add_edge(a-1,b-1)
    
  lca.from_graph2(G)

  #root = argmax([len(G[i]) for i in range(N)])
  lca.build(0)
  csum,cnum,d = bfs(lca.G2,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
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] = 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
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 = [tmp1[tmp1[j]] if tmp1[j]!=-1 else 0 for j in range(self.N)]
            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()