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:
import sys
sys.setrecursionlimit(10**7)

def main0(n,g,xyuv):
  # LCAを求める。自作する。
  # 各頂点の深さ。根は深さ0
  depth=[0]*n
  tour=[]
  hatsu=[0]*n
  dist=[0]*n
  tmp=0
  def et(p,v,tour,tmp,pc,pd):
    hatsu[v]=len(tour)-1
    for nv,c,d in g[v]:
      if nv==p:continue
      depth[nv]=depth[v]+1
      tmp+=d
      dist[nv]=tmp
      tour.append((nv,c,d))
      tour=et(v,nv,tour,tmp,c,d)
      tmp-=d
      tour.append((v,c,-d))
    return tour
  tour.append((0,0,0))
  tour=et(-1,0,tour,0,0,0)
  class SegmentTree():
    def __init__(self,size,f=lambda x,y:x+y,default=0):
      self.size=pow(2,(size-1).bit_length())
      self.f=f
      self.default=default
      self.data=[default]*(self.size*2)
    def update(self,i,x):
      i+=self.size
      self.data[i]=x
      while i:
        i>>=1
        self.data[i]=self.f(self.data[i*2],self.data[i*2+1])
    # 区間[l,r)へのクエリ
    def query(self,l,r):
      l,r=l+self.size,r+self.size
      lret,rret=self.default,self.default
      while l<r:
        if l&1:
          lret=self.f(self.data[l],lret)
          l+=1
        if r&1:
          r-=1
          rret=self.f(self.data[r],rret)
        l>>=1
        r>>=1
      return self.f(lret,rret)

  def func(x,y):
    if x[0]<y[0]:return x
    return y
  st=SegmentTree(len(tour),func,(n+1,0))
  for i,x in enumerate(tour):
    v=x[0]
    st.update(i,(depth[v],v))
  def lca(u,v):
    x,y=hatsu[u],hatsu[v]
    if x<y:
      y+=1
    else:
      x,y=y,x
      y+=1
    return st.query(x,y)[1]
  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]
  ret=[]
  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:
      ret.append(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,w)
    ret.append(uvlen-uvsum+uvnum*y)
  return ret

if __name__=='__main__':
  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))
  ary0=main0(n,g,xyuv)
  print(*ary0,sep='\n')

Submission status: Wrong Answer

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
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
    tmp+=d
    dist[nv]=tmp
    tour=et(v,nv,tour)
    tmp-=d
    tour.append((nv,c,-d))
  return tour
tour.append((0,0,0))
tour=et(-1,0,tour)


class SegmentTree():
  def __init__(self,size,f=lambda x,y:x+y,default=0):
    self.size=pow(2,(size-1).bit_length())
    self.f=f
    self.default=default
    self.data=[default]*(self.size*2)
  def update(self,i,x):
    i+=self.size
    self.data[i]=x
    while i:
      i>>=1
      self.data[i]=self.f(self.data[i*2],self.data[i*2+1])
  # 区間[l,r)へのクエリ
  def query(self,l,r):
    l,r=l+self.size,r+self.size
    lret,rret=self.default,self.default
    while l<r:
      if l&1:
        lret=self.f(self.data[l],lret)
        l+=1
      if r&1:
        r-=1
        rret=self.f(self.data[r],rret)
      l>>=1
      r>>=1
    return self.f(lret,rret)

def func(x,y):
  if x[0]<y[0]:return x
  return y
st=SegmentTree(len(tour),func,(n+1,0))
for i,x in enumerate(tour):
  v=x[0]
  st.update(i,(depth[v],v))
def lca(u,v):
  return st.query(hatsu[u],hatsu[v]+1)[1]

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)

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

"""

Submission status: Wrong Answer

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,0,0))
tour=et(-1,0,tour)


class SegmentTree():
  def __init__(self,size,f=lambda x,y:x+y,default=0):
    self.size=pow(2,(size-1).bit_length())
    self.f=f
    self.default=default
    self.data=[default]*(self.size*2)
  def update(self,i,x):
    i+=self.size
    self.data[i]=x
    while i:
      i>>=1
      self.data[i]=self.f(self.data[i*2],self.data[i*2+1])
  # 区間[l,r)へのクエリ
  def query(self,l,r):
    l,r=l+self.size,r+self.size
    lret,rret=self.default,self.default
    while l<r:
      if l&1:
        lret=self.f(self.data[l],lret)
        l+=1
      if r&1:
        r-=1
        rret=self.f(self.data[r],rret)
      l>>=1
      r>>=1
    return self.f(lret,rret)
  def get(self,i):
    return self.data[self.size+i]
  def add(self,i,x):
    self.update(i,self.get(i)+x)

def func(x,y):
  if x[0]<y[0]:return x
  return y
st=SegmentTree(len(tour),func,(n+1,0))
for i,x in enumerate(tour):
  v=x[0]
  st.update(i,(depth[v],v))
  #print(i,x)
def lca(u,v):
  return st.query(hatsu[u],hatsu[v]+1)[1]
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: Wrong Answer

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

    def point(self, u):
        return self.vid[u-self.decrement]

class SegmentTree:

    def __init__(self, n, op, e):
        """
        :param n: 要素数
        :param op: 二項演算
        :param e: 単位減
        """
        self.n = n
        self.op = op
        self.e = e
        self.size = 1 << (self.n - 1).bit_length()      # st[self.size + i] = array[i]
        self.tree = [self.e] * (self.size << 1)

    def built(self, array):
        """arrayを初期値とするセグメント木を構築"""
        for i in range(self.n):
            self.tree[self.size + i] = array[i]
        for i in range(self.size - 1, 0, -1):
            self.tree[i] = self.op(self.tree[i<<1], self.tree[(i<<1)|1])

    def update(self, i, x):
        """i 番目の要素を x に更新　(0-indexed) """
        i += self.size
        self.tree[i] = x
        while i > 1:
            i >>= 1
            self.tree[i] = self.op(self.tree[i<<1], self.tree[(i<<1)|1])

    def get(self, l, r):
        """ [l, r)の区間取得の結果を返す　(0-indexed) """
        l += self.size
        r += self.size
        res_l = self.e
        res_r = self.e
        while l < r:
            if l & 1:
                res_l = self.op(res_l, self.tree[l])
                l += 1
            if r & 1:
                r -= 1
                res_r = self.op(self.tree[r], res_r)
            l >>= 1
            r >>= 1
        return self.op(res_l, res_r)

    def max_right(self, l, f):
        """
        以下の条件を両方満たす r を(いずれか一つ)返す
            ・r = l or f(op(a[l], a[l + 1], ..., a[r - 1])) = true
            ・r = n or f(op(a[l], a[l + 1], ..., a[r])) = false
        """
        if l == self.n: return self.n
        l += self.size
        sm = self.e
        while True:
            while l % 2 == 0: l >>= 1
            if not f(self.op(sm, self.tree[l])):
                while l < self.size:
                    l = 2 * l
                    if f(self.op(sm, self.tree[l])):
                        sm = self.op(sm, self.tree[l])
                        l += 1
                return l - self.size
            sm = self.op(sm, self.tree[l])
            l += 1
            if (l & -l) == l: break
        return self.n

    def min_left(self, r, f):
        """
        以下の条件を両方満たす l を(いずれか一つ)返す
            ・l = r or f(op(a[l], a[l + 1], ..., a[r - 1])) = true
            ・l = 0 or f(op(a[l - 1], a[l], ..., a[r - 1])) = false
        """
        if r == 0: return 0
        r += self.size
        sm = self.e
        while True:
            r -= 1
            while r > 1 and (r % 2): r >>= 1
            if not f(self.op(self.tree[r], sm)):
                while r < self.size:
                    r = 2 * r + 1
                    if f(self.op(self.tree[r], sm)):
                        sm = self.op(self.tree[r], sm)
                        r -= 1
                return r + 1 - self.size
            sm = self.op(self.tree[r], sm)
            if (r & -r) == r: break
        return 0

    def __iter__(self):
        for a in self.tree[self.size:self.size+self.n]:
            yield a

    def __str__(self):
        return str(self.tree[self.size:self.size+self.n])

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

N, Q = map(int, input().split())
tree = Tree(N)
edges, query = [], [[] for _ in range(N)]
for _ in range(N-1):
    a, b, c, d = map(int, input().split())
    edges.append((a, b, c-1, d))
for i in range(Q):
    c, y, u, v = map(int, input().split())
    query[c-1].append((y, u, v, i))
tree.add_edges(edges)
tree.set_root(1)
hld = tree.heavy_light_decomposition()

e = (0, 0)
op = lambda x, y: (x[0]+y[0], x[1]+y[1])
st = SegmentTree(N, op, e)
res = [0]*Q
for p in range(N):
    st.update(tree.point(p+1), (tree.cost[p],0))
for c in range(N):
    for p in tree.color[c]:
        st.update(tree.point(p+1), (0,1))
    for y, u, v, i in query[c]:
        for l, r in tree.path_to_list(u, v):
            cost, cnt = st.get(l, r)
            res[i] += cost + cnt*y
    for p in tree.color[c]:
        st.update(tree.point(p+1), (tree.cost[p],0))

print(*res, sep="\n")

Submission status: Wrong Answer

Solution code:
import sys
import math
from collections import defaultdict

input = sys.stdin.readline
N, Q = map(int, input().split())
abcd = [list(map(int, input().split())) for _ in range(N-1)]

g = [[] for _ in range(N)]
for a, b, c, d in abcd:
    g[a-1].append((b-1, c, d))
    g[b - 1].append((a - 1, c, d))

children = [[] for _ in range(N)]
parents = [[] for _ in range(N)] # 先祖(自分を含む)
distance = [math.inf] * N  # rootへの距離
distance_by_color = [defaultdict(lambda:(0, 0)) for _ in range(N)]  # rootへの色ごとの(辺の数, 距離)
# nodeid, parents, dist, dist_by_color
q = [(0, [0], 0, defaultdict(lambda:(0, 0)))]
while len(q) > 0:
    v, p, dist, dist_c = q.pop()
    parents[v] = p
    distance[v] = dist
    distance_by_color[v] = dist_c
    for u, c, d in g[v]:
        p__ = p[-2] if len(p) >= 2 else None
        if u != p__:
            dist_c_ = dist_c.copy()
            dist_c_[c] = (dist_c_[c][0] + 1, dist_c_[c][1] + d)
            p_ = p + [u]
            q.append((u, p_, dist + d, dist_c_))
            children[v].append(u)


def is_ok(mid, parents1, parents2):
    try:
        return parents1[mid] == parents2[mid]
    except IndexError:
        return False

def lca(parents1, parents2):
    ng = min(len(parents1), len(parents2)) + 1
    ok = 0
    while (abs(ok - ng) > 1):
        mid = (ok + ng) // 2
        if is_ok(mid, parents1, parents2):
            ok = mid
        else:
            ng = mid
    return ok

def color_diff(edges_info, y):
    return edges_info[0] * y - edges_info[1]

for _ in range(Q):
    x, y, u, v = map(int, input().split())
    u -= 1
    v -= 1
    ans = 0
    p = lca(parents[u], parents[v])
    ans += distance[u]
    ans += distance[v]
    ans -= 2 * distance[p]
    ans += color_diff(distance_by_color[u][x], y)
    ans += color_diff(distance_by_color[v][x], y)
    ans -= 2 * color_diff(distance_by_color[p][x], y)
    print(ans)

Submission status: Wrong Answer

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)
    '''
    ans[i] = w
  print(*ans,sep='\n')
    
if __name__=="__main__":
  main()

Submission status: Wrong Answer

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
    prev = [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_
          prev[b] = a
          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,prev
  
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)])
  csum,cnum,d,prev = bfs(G,root)
  lca = LCA(G,root)
  lca.parent[0] = prev
  lca.depth = d
  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()