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.

Solution in Rust (1.15.1) (judge verdict: Accepted)

#[doc = " https://github.com/hatoo/competitive-rust-snippets"]
#[allow(unused_imports)]
use std::cmp::{max, min, Ordering};
#[allow(unused_imports)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
#[allow(unused_imports)]
use std::io::{stdin, stdout, BufWriter, Write};
#[allow(unused_imports)]
use std::iter::FromIterator;
#[macro_export]
macro_rules ! chmax { ( $ x : expr , $ ( $ v : expr ) ,+ ) => { $ ( $ x = std :: cmp :: max ( $ x ,$ v ) ; ) + } ; }
#[macro_export]
macro_rules ! chmin { ( $ x : expr , $ ( $ v : expr ) ,+ ) => { $ ( $ x = std :: cmp :: min ( $ x ,$ v ) ; ) + } ; }
#[macro_export]
macro_rules ! max { ( $ x : expr ) => ( $ x ) ; ( $ x : expr , $ ( $ xs : expr ) ,+ ) => { std :: cmp :: max ( $ x , max ! ( $ ( $ xs ) ,+ ) ) } ; }
#[macro_export]
macro_rules ! min { ( $ x : expr ) => ( $ x ) ; ( $ x : expr , $ ( $ xs : expr ) ,+ ) => { std :: cmp :: min ( $ x , min ! ( $ ( $ xs ) ,+ ) ) } ; }
#[macro_export]
macro_rules ! dvec { ( $ t : expr ; $ len : expr ) => { vec ! [ $ t ; $ len ] } ; ( $ t : expr ; $ len : expr , $ ( $ rest : expr ) ,* ) => { vec ! [ dvec ! ( $ t ; $ ( $ rest ) ,* ) ; $ len ] } ; }
#[allow(unused_macros)]
macro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { eprintln ! ( concat ! ( $ ( stringify ! ( $ a ) , " = {:?}, " ) ,* ) , $ ( $ a ) ,* ) ; } }
#[macro_export]
macro_rules ! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut parser = Parser :: from_str ( $ s ) ; input_inner ! { parser , $ ( $ r ) * } } ; ( parser = $ parser : ident , $ ( $ r : tt ) * ) => { input_inner ! { $ parser , $ ( $ r ) * } } ; ( new_stdin_parser = $ parser : ident , $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let reader = std :: io :: BufReader :: new ( stdin . lock ( ) ) ; let mut $ parser = Parser :: new ( reader ) ; input_inner ! { $ parser , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { input ! { new_stdin_parser = parser , $ ( $ r ) * } } ; }
#[macro_export]
macro_rules ! input_inner { ( $ parser : ident ) => { } ; ( $ parser : ident , ) => { } ; ( $ parser : ident , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ parser , $ t ) ; input_inner ! { $ parser $ ( $ r ) * } } ; }
#[macro_export]
macro_rules ! read_value { ( $ parser : ident , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ parser , $ t ) ) ,* ) } ; ( $ parser : ident , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ parser , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ parser : ident , chars ) => { read_value ! ( $ parser , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ parser : ident , usize1 ) => { read_value ! ( $ parser , usize ) - 1 } ; ( $ parser : ident , $ t : ty ) => { $ parser . next ::<$ t > ( ) . expect ( "Parse error" ) } ; }
use std::io;
use std::io::BufRead;
use std::str;
pub struct Parser<R> {
    reader: R,
    buf: Vec<u8>,
    pos: usize,
}
impl Parser<io::Empty> {
    pub fn from_str(s: &str) -> Parser<io::Empty> {
        Parser {
            reader: io::empty(),
            buf: s.as_bytes().to_vec(),
            pos: 0,
        }
    }
}
impl<R: BufRead> Parser<R> {
    pub fn new(reader: R) -> Parser<R> {
        Parser {
            reader: reader,
            buf: vec![],
            pos: 0,
        }
    }
    pub fn update_buf(&mut self) {
        self.buf.clear();
        self.pos = 0;
        loop {
            let (len, complete) = {
                let buf2 = self.reader.fill_buf().unwrap();
                self.buf.extend_from_slice(buf2);
                let len = buf2.len();
                if len == 0 {
                    break;
                }
                (len, buf2[len - 1] <= 0x20)
            };
            self.reader.consume(len);
            if complete {
                break;
            }
        }
    }
    pub fn next<T: str::FromStr>(&mut self) -> Result<T, T::Err> {
        loop {
            let mut begin = self.pos;
            while begin < self.buf.len() && (self.buf[begin] <= 0x20) {
                begin += 1;
            }
            let mut end = begin;
            while end < self.buf.len() && (self.buf[end] > 0x20) {
                end += 1;
            }
            if begin != self.buf.len() {
                self.pos = end;
                return str::from_utf8(&self.buf[begin..end]).unwrap().parse::<T>();
            } else {
                self.update_buf();
            }
        }
    }
}
#[allow(unused_macros)]
macro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { eprintln ! ( concat ! ( $ ( stringify ! ( $ a ) , " = {:?}, " ) ,* ) , $ ( $ a ) ,* ) ; } }
#[doc = " https://github.com/hatoo/competitive-rust-snippets"]
const BIG_STACK_SIZE: bool = true;
#[allow(dead_code)]
fn main() {
    use std::thread;
    if BIG_STACK_SIZE {
        thread::Builder::new()
            .stack_size(32 * 1024 * 1024)
            .name("solve".into())
            .spawn(solve)
            .unwrap()
            .join()
            .unwrap();
    } else {
        solve();
    }
}
struct EdgeSum {
    cnt: Vec<usize>,
    dst: Vec<usize>,
}
fn solve() {
    let out = stdout();
    let mut out = BufWriter::new(out.lock());
    input!{
        n:usize,q:usize,
        abcd:[(usize,usize,usize,i64);n-1],
        xyuv:[(usize,i64,usize,usize);q],
    }

    let mut hld = HLDecomposition::new(n);
    for i in 0..n-1 {
        let (a,b,_,_) = abcd[i];
        hld.connect(a-1, b-1);
    }
    hld.build(0);

    let mut color2qi = HashMap::new();
    for i in 0..q {
        let (x,y,u,v) = xyuv[i];
        color2qi.entry(x).or_insert(vec![]).push(i);
    }

    // 色関係なしのウェイト
    let mut distseg: SEG<SUM> = SEG::new(n);
    let mut color2ei = HashMap::new();
    let mut ei2weight = HashMap::new();
    for i in 0..n-1 {
        let (a,b,c,d) = abcd[i];
        let va = hld.real_to_virt[a-1];
        let vb = hld.real_to_virt[b-1];
        let ei = max(va,vb); // エッジ番号
        color2ei.entry(c).or_insert(vec![]).push(ei);
        ei2weight.insert(ei, d);
        distseg.update(ei, d);
    }

    // ある色のカウント
    let mut cntseg: SEG<SUM> = SEG::new(n);
    // ある色のウェイト
    let mut weightseg: SEG<SUM> = SEG::new(n);

    let mut ans = vec![0;q];
    for c in 1..n {
        // init
        for &ei in color2ei.get(&c).unwrap_or(&vec![]) {
            cntseg.update(ei, 1);
            weightseg.update(ei, *ei2weight.get(&ei).unwrap());
        }
        for &qi in color2qi.get(&c).unwrap_or(&vec![]) {
            let (x,y,u,v) = xyuv[qi];
            let mut cntsum = 0;
            let mut weightsum = 0;
            let mut actualweight = 0;
            for (l,r) in hld.edge_decomposition_between(u-1, v-1) {
                actualweight += distseg.query(l, r+1);
                cntsum += cntseg.query(l, r+1);
                weightsum += weightseg.query(l, r+1);
            }
            ans[qi] = actualweight - weightsum + y * cntsum;
        }
        for &ei in color2ei.get(&c).unwrap_or(&vec![]) {
            cntseg.update(ei, 0);
            weightseg.update(ei, 0);
        }
    }
    for x in ans {
        writeln!(out, "{}",x);
    }
}

#[allow(dead_code)]
pub trait Monoid {
    type T: Clone;
    fn id() -> Self::T;
    fn op(a: &Self::T, b: &Self::T) -> Self::T;
}
#[allow(dead_code)]
pub struct SEG<M: Monoid> {
    n: usize,
    buf: Vec<M::T>,
}
impl<M: Monoid> SEG<M> {
    #[allow(dead_code)]
    pub fn new(n: usize) -> SEG<M> {
        let mut m = 1;
        while m < n {
            m *= 2;
        }
        SEG {
            n: m,
            buf: vec![M::id().clone(); 2 * m],
        }
    }
    #[allow(dead_code)]
    pub fn update(&mut self, k: usize, a: M::T) {
        let mut k = k + self.n;
        self.buf[k] = a;
        while k > 1 {
            k = k >> 1;
            self.buf[k] = M::op(&self.buf[k * 2], &self.buf[k * 2 + 1]);
        }
    }
    #[allow(dead_code)]
    pub fn get(&self, k: usize) -> M::T {
        self.buf[k + self.n].clone()
    }
    pub fn do_query(&self, a: usize, b: usize, k: usize, l: usize, r: usize) -> M::T {
        if r <= a || b <= l {
            return M::id();
        }
        if a <= l && r <= b {
            return self.buf[k].clone();
        } else {
            let vl = self.do_query(a, b, k * 2, l, (l + r) / 2);
            let vr = self.do_query(a, b, k * 2 + 1, (l + r) / 2, r);
            return M::op(&vl, &vr);
        }
    }
    #[allow(dead_code)]
    pub fn query(&self, a: usize, b: usize) -> M::T {
        self.do_query(a, b, 1, 0, self.n)
    }
}

#[allow(dead_code)]
struct SUM;
impl Monoid for SUM {
    type T = i64;
    fn id() -> Self::T {
        0
    }
    fn op(a: &Self::T, b: &Self::T) -> Self::T {
        *a + *b
    }
}

struct HLDecomposition {
    n: usize,
    g: Vec<Vec<usize>>,
    subcnt: Vec<usize>,
    depth: Vec<usize>,
    pub par: Vec<Option<usize>>,
    heavy_next: Vec<Option<usize>>,
    heavy_head: Vec<usize>,
    real_to_virt: Vec<usize>,
    pub virt_to_real: Vec<usize>,
}

impl HLDecomposition {
    pub fn new(n: usize) -> Self {
        HLDecomposition {
            n: n,
            g: vec![vec![]; n],
            subcnt: vec![0; n],
            depth: vec![0; n],
            par: vec![None; n],
            heavy_next: vec![None; n],
            heavy_head: vec![n; n],
            real_to_virt: vec![n; n],
            virt_to_real: vec![n; n],
        }
    }

    pub fn connect(&mut self, u: usize, v: usize) {
        self.g[u].push(v);
        self.g[v].push(u);
    }

    #[doc = "O(N)"]
    pub fn build(&mut self, root: usize) {
        self.dfs1(root);
        self.dfs2(root);
        self.bfs(root);
    }

    // 部分木の大きさを計算する
    fn dfs1(&mut self, root: usize) {
        self.depth[root] = 0;
        self.par[root] = None;
        self.dfs1_sub(root, None);
    }
    fn dfs1_sub(&mut self, u: usize, par: Option<usize>) -> usize {
        let mut cnt = 1;
        for v in self.g[u].clone() {
            if Some(v) == par { continue; }
            self.depth[v] = self.depth[u] + 1;
            self.par[v] = Some(u);
            cnt += self.dfs1_sub(v, Some(u));
        }
        self.subcnt[u] = cnt;
        cnt
    }
    
    // ヘビーパスを探す
    fn dfs2(&mut self, root: usize) {
        self.dfs2_sub(root, None);
    }
    fn dfs2_sub(&mut self, u: usize, par: Option<usize>) {
        let mut maxv = 0;
        let mut heavy_next = None;

        let cld = self.g[u].clone();

        // ヘビーパスを決める
        for &v in &cld {
            if Some(v) == par { continue; }
            if self.subcnt[v] > maxv { 
                maxv = self.subcnt[v];
                heavy_next = Some(v);
            }
        }
        // ヘビーパスがあるならそれを伸ばす
        if let Some(hn) = heavy_next {
            self.heavy_next[u] = Some(hn);
            self.dfs2_sub(hn, Some(u));
        }
        // ライトパスはまたルートからやり直し
        for &v in &cld {
            if Some(v) == par || Some(v) == heavy_next { continue; }
            self.dfs2_sub(v, Some(u));
        }
    }

    fn bfs(&mut self, root: usize) {
        let mut cur_virt_id = 0;
        let mut q = VecDeque::new();
        q.push_back(root);
        // ヘビーパスの先頭から下っていく
        while let Some(h) = q.pop_front() {
            let mut cur0 = Some(h);
            while cur0.is_some() {
                let cur = cur0.unwrap();
                self.real_to_virt[cur] = cur_virt_id;
                self.virt_to_real[cur_virt_id] = cur;
                cur_virt_id += 1;
                self.heavy_head[cur] = h;
                for v in self.g[cur].clone() {
                    if Some(v) == self.par[cur] || Some(v) == self.heavy_next[cur] { continue; }
                    q.push_back(v);
                }
                cur0 = self.heavy_next[cur];
            }
        }
    }

    #[doc = "O(log N)"]
    pub fn lca(&self, u: usize, v: usize) -> usize {
        let mut l = u;
        let mut r = v;
        loop {
            if self.real_to_virt[l] > self.real_to_virt[r] {
                std::mem::swap(&mut l, &mut r);
            }
            // 同じヘビーパスの上に乗っている
            // よって、vidの低い方がLCAと確定する
            if self.heavy_head[l] == self.heavy_head[r] {
                return l;
            }
            // 一つ上のヘビーパスに移る
            r = self.par[self.heavy_head[r]].unwrap();
        }
    }

    #[doc = "returns a list of [l,r]. O(N)"]
    pub fn vertex_decomposition(&self) -> Vec<(usize, usize)> {
        let mut vhead = vec![self.n; self.n];
        for i in 0..self.n {
            vhead[i] = self.real_to_virt[self.heavy_head[i]];
        }
        let mut hs = std::collections::HashMap::new();
        for x in vhead {
            *hs.entry(x).or_insert(0) += 1;
        }
        let mut res = vec![];
        for (k,v) in hs {
            res.push((k,k+v-1));
        }
        res
    }

    #[doc = "return a list of [l,r]. edge is represented by the child with larger virtual id. O(N)"]
    pub fn edge_decomposition(&self) -> Vec<(usize,usize)> {
        let V = self.vertex_decomposition();
        let mut res = vec![];
        for (u,v) in V {
            let u = if u==0 {
                1
            } else {
                u
            };
            res.push((u,v));
        }
        res
    }

    #[doc = "O(logN)"]
    pub fn vertex_decomposition_between(&self, u: usize, v: usize) -> Vec<(usize, usize)> {
        let mut res = vec![];

        let mut l = u;
        let mut r = v;
        loop {
            if self.real_to_virt[l] > self.real_to_virt[r] {
                std::mem::swap(&mut l, &mut r);
            }
            let p = (std::cmp::max(self.real_to_virt[self.heavy_head[r]], self.real_to_virt[l]), self.real_to_virt[r]);
            res.push(p);
            if self.heavy_head[l] != self.heavy_head[r] {
                r = self.par[self.heavy_head[r]].unwrap();
            } else { break; }
        }

        res
    }

    #[doc = "O(logN)"]
    pub fn edge_decomposition_between(&self, u: usize, v: usize) -> Vec<(usize, usize)> {
        let mut res = vec![];

        let mut l = u;
        let mut r = v;
        loop {
            if self.real_to_virt[l] > self.real_to_virt[r] {
                std::mem::swap(&mut l, &mut r);
            }
            if self.heavy_head[l] != self.heavy_head[r] {
                let p = (self.real_to_virt[self.heavy_head[r]], self.real_to_virt[r]);
                res.push(p);
                r = self.par[self.heavy_head[r]].unwrap();
            } else {
                if l != r {
                    let p = (self.real_to_virt[l]+1, self.real_to_virt[r]);
                    res.push(p);
                }
                break;
            }
        }

        res
    }

    pub fn distance(&self, u: usize, v: usize) -> usize {
        self.depth[u] + self.depth[v] - 2 * self.depth[self.lca(u,v)]
    }
}