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: Wrong Answer

Solution code:
from collections import defaultdict
from copy import deepcopy

def main():
    node_num, q_num = map(int, input().split())
    graph_data = defaultdict(set)
    edge_data = defaultdict(set)
    color_dist = defaultdict(int)


    for i in range(node_num - 1):
        a, b, c, d = map(int, input().split())
        graph_data[a].add(b)
        graph_data[b].add(a)
        edge_data[(a, b)] = (c, d)
        edge_data[(b, a)] = (c, d)
        color_dist[c] = d

    dist = [-1 for i in range(node_num + 1)]
    color_data = [defaultdict(int) for i in range(node_num + 1)]
    dist[1] = 0

    now_num = set()
    next_num = set()
    now_num.add(1)

    have_color = [defaultdict(int) for i in range(node_num + 1)]

    oya = [0 for i in range(node_num + 1)]
    oya[1] = 1


    while len(now_num) > 0:
        for now_ele in now_num:
            for next_ele in graph_data[now_ele]:
                if dist[next_ele] != -1:
                    continue
                # print(next_ele, now_ele)
                oya[next_ele] = now_ele
                color_data[next_ele] = deepcopy(color_data[now_ele])
                have_color[next_ele] = deepcopy(have_color[now_ele])
                # print(color_data)

                color, length = edge_data[(now_ele, next_ele)]
                dist[next_ele] = dist[now_ele] + length
                color_data[next_ele][color] += 1
                have_color[next_ele][color] += length
                next_num.add(next_ele)
        now_num = next_num
        next_num = set()

    # print(dist)
    # print(color_data)
    # print(color_dist)
    # print(have_color)

    for i in range(q_num):
        x, y, u, v = map(int, input().split())

        oya_set = set()
        u_now, v_now = u, v
        while 1:
            u_oya = oya[u_now]
            v_oya = oya[v_now]
            if u_oya in oya_set:
                oyaoya = u_oya
                break
            else:
                oya_set.add(u_oya)
            if v_oya in oya_set:
                oyaoya = v_oya
                break
            else:
                # print(v_oya)
                oya_set.add(v_oya)
            u_now, v_now = u_oya, v_oya


        u_kyori = dist[u] - (have_color[u][x] - color_data[u][x] * y)
        v_kyori = dist[v] - (have_color[v][x] - color_data[v][x] * y)
        oya_kyori = dist[oyaoya] - (have_color[oyaoya][x] - color_data[oyaoya][x] * y)
        print(abs(u_kyori + v_kyori - oya_kyori))



if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(100005)

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

n, q = na()
g = [[] for _ in range(n)]
es = []
for i in range(n-1):
    a, b, c, d = na()
    a -= 1
    b -= 1
    g[a].append(b)
    g[b].append(a)
    es.append((c, d, a, b))
es.sort()

qs = []
for i in range(q):
    x, y, u, v = na()
    qs.append((x, y, u-1, v-1, i))
qs.sort()

def addfenwick(ft, i, v):
    if v == 0 or i < 0: return
    i += 1
    while i < len(ft):
        ft[i] += v
        i += i&-i

def sumfenwick(ft, i):
    s = 0
    i += 1
    while i > 0:
        s += ft[i]
        i -= i&-i
    return s

ord = []
right = [0] * n
par = [-1] * n
dep = [0] * n

def dfs(cur, pre, g):
    global ord, right, par, dep
    ord.append(cur)
    for e in g[cur]:
        if e == pre: continue
        dep[e] = dep[cur] + 1
        dfs(e, cur, g)
        par[e] = cur
    right[cur] = len(ord)

dfs(0, -1, g)


def ntz(m):
    assert m != 0
    ret = 0
    while m&1^1:
        ret += 1
        m >>= 1
    return ret

def lca(a, b, spar, dep):
    if dep[a] < dep[b]:
        b = anc(b, dep[b] - dep[a], spar)
    else:
        a = anc(a, dep[a] - dep[b], spar)

    if a == b:
        return a

    for d in range(16, -1, -1):
        if spar[d][a] == -1: continue
        if spar[d][a] != spar[d][b]:
            a = spar[d][a]
            b = spar[d][b]
    return spar[0][a]

def anc(v, m, spar):
    for z in range(17):
        if m>>z&1:
            v = spar[z][v]
    return v

def lsp(par):
    o = len(par)
    m = 17
    pars = [[0]*o for _ in range(m)]
    pars[0] = par
    for j in range(1, m):
        for i in range(n):
            pars[j][i] = -1 if pars[j-1][i] == -1 else pars[j-1][pars[j-1][i]]
    return pars

ft = [0] * (n+5)
ftc = [0] * (n+5)

pw = [0] * n
for e in es:
    if par[e[2]] == e[3]:
        pw[e[2]] = e[1]
    else:
        pw[e[3]] = e[1]

iord = [0] * n
for i in range(n):
    iord[ord[i]] = i

for i in range(1, n):
    addfenwick(ft, iord[i], pw[i])
    addfenwick(ft, right[i], -pw[i])

anss = [0] * q

spar = lsp(par)
i = 0
p = 0
while i < q:
    j = i
    while j < q and qs[j][0] == qs[i][0]:
        j += 1

    while p < n-1 and es[p][0] < qs[i][0]:
        p += 1
    r = p
    while r < n-1 and es[r][0] <= qs[i][0]:
        x = es[r][2]
        y = es[r][3]
        z = x if par[x] == y else y
        addfenwick(ft, iord[z], -pw[z])
        addfenwick(ft, right[z], pw[z])
        addfenwick(ftc, iord[z], 1)
        addfenwick(ftc, right[z], -1)
        r += 1

    # for u in range(i, j):
    #     lc = lca(qs[u][2], qs[u][3], spar, dep)
    #     c0 = sumfenwick(ft, iord[qs[u][2]]) + sumfenwick(ft, iord[qs[u][3]]) - 2*sumfenwick(ft, iord[lc])
    #     c1 = sumfenwick(ftc, iord[qs[u][2]]) + sumfenwick(ftc, iord[qs[u][3]]) - 2*sumfenwick(ftc, iord[lc])
    #     anss[qs[u][4]] = c0 + c1 * qs[u][1]

    r = p
    while r < n-1 and es[r][0] <= qs[i][0]:
        x = es[r][2]
        y = es[r][3]
        z = x if par[x] == y else y
        addfenwick(ft, iord[z], pw[z])
        addfenwick(ft, right[z], -pw[z])
        addfenwick(ftc, iord[z], -1)
        addfenwick(ftc, right[z], 1)
        r += 1

    i = j

for v in anss:
    print(v)

Submission status: Wrong Answer

Solution code:
import sys
import io

sys.stdin = io.StringIO(
    """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"""
)

# ======================================================================

import sys
sys.setrecursionlimit(100005)

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

n, q = na()
g = [[] for _ in range(n)]
es = []
for i in range(n-1):
    a, b, c, d = na()
    a -= 1
    b -= 1
    g[a].append(b)
    g[b].append(a)
    es.append((c, d, a, b))
es.sort()

qs = []
for i in range(q):
    x, y, u, v = na()
    qs.append((x, y, u-1, v-1, i))
qs.sort()

def addfenwick(ft, i, v):
    if v == 0 or i < 0: return
    i += 1
    while i < len(ft):
        ft[i] += v
        i += i&-i

def sumfenwick(ft, i):
    s = 0
    i += 1
    while i > 0:
        s += ft[i]
        i -= i&-i
    return s

ord = []
right = [0] * n
par = [-1] * n
dep = [0] * n

def dfs(cur, pre, g):
    global ord, right, par, dep
    ord.append(cur)
    for e in g[cur]:
        if e == pre: continue
        dep[e] = dep[cur] + 1
        dfs(e, cur, g)
        par[e] = cur
    right[cur] = len(ord)

dfs(0, -1, g)


def ntz(m):
    assert m != 0
    ret = 0
    while m&1^1:
        ret += 1
        m >>= 1
    return ret

def lca(a, b, spar, dep):
    if dep[a] < dep[b]:
        b = anc(b, dep[b] - dep[a], spar)
    else:
        a = anc(a, dep[a] - dep[b], spar)

    if a == b:
        return a

    for d in range(len(spar)-1, -1, -1):
        if spar[d][a] == -1: continue
        if spar[d][a] != spar[d][b]:
            a = spar[d][a]
            b = spar[d][b]
    return spar[0][a]

def anc(a, m, spar):
    for x in range(17):
        if m>>x&1:
            a = spar[x][a]
    return a

def lsp(par):
    o = len(par)
    m = 17
    pars = [[0]*o for _ in range(m)]
    pars[0] = par
    for j in range(1, m):
        for i in range(n):
            pars[j][i] = -1 if pars[j-1][i] == -1 else pars[j-1][pars[j-1][i]]
    return pars

ft = [0] * (n+5)
ftc = [0] * (n+5)

pw = [0] * n
for e in es:
    if par[e[2]] == e[3]:
        pw[e[2]] = e[1]
    else:
        pw[e[3]] = e[1]

iord = [0] * n
for i in range(n):
    iord[ord[i]] = i

for i in range(1, n):
    addfenwick(ft, iord[i], pw[i])
    addfenwick(ft, right[i], -pw[i])

anss = [0] * q

spar = lsp(par)
i = 0
p = 0
while i < q:
    j = i
    while j < q and qs[j][0] == qs[i][0]:
        j += 1

    while p < n-1 and es[p][0] < qs[i][0]:
        p += 1
    r = p
    while r < n-1 and es[r][0] <= qs[i][0]:
        x = es[r][2]
        y = es[r][3]
        z = x if par[x] == y else y
        addfenwick(ft, iord[z], -pw[z])
        addfenwick(ft, right[z], pw[z])
        addfenwick(ftc, iord[z], 1)
        addfenwick(ftc, right[z], -1)
        r += 1

    # for u in range(i, j):
    #     lc = lca(qs[u][2], qs[u][3], spar, dep)
    #     c0 = sumfenwick(ft, iord[qs[u][2]]) + sumfenwick(ft, iord[qs[u][3]]) - 2*sumfenwick(ft, iord[lc])
    #     c1 = sumfenwick(ftc, iord[qs[u][2]]) + sumfenwick(ftc, iord[qs[u][3]]) - 2*sumfenwick(ftc, iord[lc])
    #     anss[qs[u][4]] = c0 + c1 * qs[u][1]

    r = p
    while r < n-1 and es[r][0] <= qs[i][0]:
        x = es[r][2]
        y = es[r][3]
        z = x if par[x] == y else y
        addfenwick(ft, iord[z], pw[z])
        addfenwick(ft, right[z], -pw[z])
        addfenwick(ftc, iord[z], -1)
        addfenwick(ftc, right[z], 1)
        r += 1

    i = j

for v in anss:
    print(v)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**7)

n,q=map(int,input().split())
abcd=[list(map(int,input().split())) for _ in range(n-1)]
xyuv=[list(map(int,input().split())) for _ in range(q)]
g=[[] for _ in range(n)]
for a,b,c,d in abcd:
  a,b=a-1,b-1
  g[a].append((b,c,d))
  g[b].append((a,c,d))
# LCAを求める。自作する。
# 頂点0を根としたときの頂点iの親
par=[i for i in range(n)]
# 各頂点の深さ。根は深さ0
depth=[0]*n
tour=[]
hatsu=[0]*n
dist=[0]*n
tmp=0
def et(p,v,tour):
  global tmp
  for nv,c,d in g[v]:
    if nv==p:continue
    hatsu[nv]=len(tour)
    tour.append((nv,c,d))
    depth[nv]=depth[v]+1
    par[nv]=v
    tmp+=d
    dist[nv]=tmp
    tour=et(v,nv,tour)
    tmp-=d
    tour.append((nv,c,-d))
  return tour
tour.append((0,None,None))
tour=et(-1,0,tour)
def lca(u,v):
  if depth[v]<depth[u]:u,v=v,u
  while u!=v:
    if depth[v]<depth[u]:u,v=v,u
    v=par[v]
  return v
dc={}
dcary={}
for i,(v,c,d) in enumerate(tour):
  if c in dc:
    ci=1 if d>0 else -1
    dc[c].append((dc[c][-1][0]+ci,dc[c][-1][1]+d))
    dcary[c].append(i)
  else:
    dc[c]=[(0,0),(1,d)]
    dcary[c]=[0,i]
from bisect import bisect_right as bl
for x,y,u,v in xyuv:
  u,v=u-1,v-1
  w=lca(u,v)
  uvlen=dist[u]+dist[v]-dist[w]*2
  if x not in dc:
    print(uvlen)
    continue
  widx=bl(dcary[x],hatsu[w])-1
  wnum,wsum=dc[x][widx]
  uidx=bl(dcary[x],hatsu[u])-1
  vidx=bl(dcary[x],hatsu[v])-1
  unum,usum=dc[x][uidx]
  vnum,vsum=dc[x][vidx]
  uvsum=usum+vsum-wsum*2
  uvnum=unum+vnum-wnum*2
  #print(uvlen-uvsum+uvnum*y,uvlen,usum,vsum,wsum,uvnum)
  print(uvlen-uvsum+uvnum*y)
exit()
for k in dc:
  print('=====',k,'=====')
  print(dcary[k])
  print(dc[k])
print(hatsu)

Submission status: Time Limit Exceeded

Solution code:
class Tree():
    def __init__(self, n, decrement=1):
        self.n = n
        self.edges = [[] for _ in range(n)]
        self.edges2 = [[] for _ in range(n)]
        self.root = None
        self.depth = [-1]*n
        self.size = [1]*n       # 部分木のノードの数
        self.color = [[] for _ in range(n)]
        self.cost = [0]*n
        self.decrement = decrement

    def add_edge(self, u, v):
        u, v = u-self.decrement, v-self.decrement
        self.edges[u].append(v)
        self.edges[v].append(u)

    def add_edges(self, edges):
        for u, v, c, d in edges:
            u, v = u-self.decrement, v-self.decrement
            self.edges[u].append(v)
            self.edges[v].append(u)
            self.edges2[u].append((v, c, d))
            self.edges2[v].append((u, c, d))

    def set_root(self, root):
        root -= self.decrement
        self.root = root
        self.par = [-1]*self.n
        self.depth[root] = 0
        self.order = [root]     # 帰りがけに使う
        next_set = [root]
        while next_set:
            p = next_set.pop()
            for q, c, d in self.edges2[p]:
                if self.depth[q] != -1: continue
                self.par[q] = p
                self.color[c].append(q)
                self.cost[q] = d
                self.depth[q] = self.depth[p]+1
                self.order.append(q)
                next_set.append(q)
        for p in self.order[::-1]:
            for q in self.edges[p]:
                if self.par[p] == q: continue
                self.size[p] += self.size[q]

    def heavy_light_decomposition(self):
        """
        heavy edge を並べてリストにした物を返す (1-indexed if decrement=True)
        """
        # assert self.root is not None
        self.vid = [-1]*self.n
        self.hld = [-1]*self.n
        self.head = [-1]*self.n
        self.head[self.root] = self.root
        self.heavy_node = [-1]*self.n
        next_set = [self.root]
        for i in range(self.n):
            """ for tree graph, dfs ends in N times """
            p = next_set.pop()
            self.vid[p] = i
            self.hld[i] = p+self.decrement
            maxs = 0
            for q in self.edges[p]:
                """ encode direction of Heavy edge into heavy_node """
                if self.par[p] == q: continue
                if maxs < self.size[q]:
                    maxs = self.size[q]
                    self.heavy_node[p] = q
            for q in self.edges[p]:
                """ determine "head" of heavy edge """
                if self.par[p] == q or self.heavy_node[p] == q: continue
                self.head[q] = q
                next_set.append(q)
            if self.heavy_node[p] != -1:
                self.head[self.heavy_node[p]] = self.head[p]
                next_set.append(self.heavy_node[p])
        return self.hld

    def lca(self, u, v):
        # assert self.head is not None
        u, v = u-self.decrement, v-self.decrement
        while True:
            if self.vid[u] > self.vid[v]: u, v = v, u
            if self.head[u] != self.head[v]:
                v = self.par[self.head[v]]
            else:
                return u + self.decrement

    def distance(self, u, v):
        # assert self.head is not None
        p = self.lca(u, v)
        u, v, p = u-self.decrement, v-self.decrement, p-self.decrement
        return self.depth[u] + self.depth[v] - 2*self.depth[p]

    def find(self, u, v, x):
        return self.distance(u,x)+self.distance(x,v)==self.distance(u,v)

    def path_to_list(self, u, v):
        """
        パス上の頂点の集合を self.hld 上の開区間の集合として表す
        ここで、self.hld は heavy edge を並べて数列にしたものである
        """
        # assert self.head is not None
        u, v = u-self.decrement, v-self.decrement
        while True:
            if self.vid[u] > self.vid[v]: u, v = v, u
            if self.head[u] != self.head[v]:
                yield self.vid[self.head[v]], self.vid[v] + 1
                v = self.par[self.head[v]]
            else:
                yield self.vid[u], self.vid[v] + 1
                return

#########################################################################################################
import sys
input = sys.stdin.readline

N, Q = map(int, input().split())
T = Tree(N)
edges = []
for _ in range(N-1):
    a, b, c, d = map(int, input().split())
    edges.append((a, b, c, d))
T.add_edges(edges)
T.set_root(1)
hld = T.heavy_light_decomposition()
S = [0]
for p in hld:
    S.append(S[-1]+T.cost[p-1])
for _ in range(Q):
    x, y, u, v = map(int, input().split())
    res = 0
    for l, r in  T.path_to_list(u, v):
        res += S[r]-S[l]
    for p in T.color[x]:
        if T.find(u, v, p+1): res += y-T.cost[p]
    print(res)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**7)

n,q=map(int,input().split())
abcd=[list(map(int,input().split())) for _ in range(n-1)]
xyuv=[list(map(int,input().split())) for _ in range(q)]
g=[[] for _ in range(n)]
for a,b,c,d in abcd:
  a,b=a-1,b-1
  g[a].append((b,c,d))
  g[b].append((a,c,d))
# LCAを求める。自作する。
# 頂点0を根としたときの頂点iの親
par=[i for i in range(n)]
# 各頂点の深さ。根は深さ0
depth=[0]*n
tour=[]

colorsum=[[] for _ in range(n)]
colornum=[[] for _ in range(n)]
colorsum[0]=[0]*n
colornum[0]=[0]*n
dist=[0]*n
tmpnum,tmpsum=[0]*n,[0]*n
def et(p,v,tour):
  for nv,c,d in g[v]:
    if nv==p:continue
    tour.append((nv,c,d))
    depth[nv]=depth[v]+1
    par[nv]=v
    tmpnum[c]+=1
    tmpsum[c]+=d
    colornum[nv]=tmpnum.copy()
    colorsum[nv]=tmpsum.copy()
    dist[nv]=sum(tmpsum)
    tour=et(v,nv,tour)
    tmpnum[c]-=1
    tmpsum[c]-=d
    tour.append((nv,c,-d))
  return tour
tour.append((0,None,None))
tour=et(-1,0,tour)
def lca(u,v):
  if depth[v]<depth[u]:u,v=v,u
  while u!=v:
    if depth[v]<depth[u]:u,v=v,u
    v=par[v]
  return v
for x,y,u,v in xyuv:
  u,v=u-1,v-1
  w=lca(u,v)
  uvlen=dist[u]+dist[v]-dist[w]*2
  uvsum=colorsum[u][x]+colorsum[v][x]-colorsum[w][x]*2
  uvnum=colornum[u][x]+colornum[v][x]-colornum[w][x]*2
  print(uvlen-uvsum+uvnum*y)

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):
        from copy import deepcopy
        #self.root = root
        self._bfs()
        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[0][u]
        
                
    def _bfs(self):
        from collections import deque
        seen = [0]*self.N
        self.d = [0]*self.N
        self.prev = [-1]*self.N
        todo = deque()
        seen[0]=1
        todo.append(0)
        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():
    N = len(G)
    seen = [0]*N
    csum = [{} for _ in range(N)]
    cnum = [{} for _ in range(N)]
    d = [0]*N
    todo = deque()
    seen[0]=1
    todo.append(0)
    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.from_graph(G)
lca.build()
csum,cnum,d = bfs()
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("\n".join(map(str,ans)))

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)]
        self.G = G
    
    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):
        from copy import deepcopy
        #self.root = root
        self._bfs()
        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[0][u]
                
    def _bfs(self):
        from collections import deque
        seen = [0]*self.N
        self.d = [0]*self.N
        self.prev = [-1]*self.N
        todo = deque()
        seen[0]=1
        todo.append(0)
        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():
    N = len(G)
    seen = [0]*N
    todo = deque()
    seen[0]=1
    todo.append(0)
    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
  
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.from_graph(G)
lca.build()
csum = [{} for _ in range(N)]
cnum = [{} for _ in range(N)]
d = [0]*N
bfs()
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)

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):
        from copy import deepcopy
        #self.root = root
        self._bfs()
        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[0][u]
        
                
    def _bfs(self):
        from collections import deque
        seen = [0]*self.N
        self.d = [0]*self.N
        self.prev = [-1]*self.N
        todo = deque()
        seen[0]=1
        todo.append(0)
        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():
    N = len(G)
    seen = [0]*N
    csum = [{} for _ in range(N)]
    cnum = [{} for _ in range(N)]
    d = [0]*N
    todo = deque()
    seen[0]=1
    todo.append(0)
    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.from_graph(G)
lca.build()
csum,cnum,d = bfs()
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')