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)

//---------- begin SegmentTree Point update Range query ----------
mod segment_tree {
    pub struct PURQ<T: Clone, F: Fn(T, T) -> T> {
        n: usize,
        a: Vec<T>,
        id: T,
        op: F,
    }
    #[allow(dead_code)]
    impl<T: Clone, F: Fn(T, T) -> T> PURQ<T, F> {
        pub fn new(n: usize, id: T, op: F) -> PURQ<T, F> {
            let mut k = 1;
            while k < n {
                k *= 2;
            }
            PURQ {
                n: k,
                a: vec![id.clone(); 2 * k],
                id: id,
                op: op,
            }
        }
        pub fn update(&mut self, x: usize, v: T) {
            let mut k = self.n + x;
            let a = &mut self.a;
            a[k] = v;
            k >>= 1;
            while k > 0 {
                a[k] = (self.op)(a[2 * k].clone(), a[2 * k + 1].clone());
                k >>= 1;
            }
        }
        pub fn update_tmp(&mut self, x: usize, v: T) {
            self.a[x + self.n] = v;
        }
        pub fn update_all(&mut self) {
            for k in (1..(self.n)).rev() {
                self.a[k] = (self.op)(self.a[2 * k].clone(), self.a[2 * k + 1].clone());
            }
        }
        pub fn find(&self, mut l: usize, mut r: usize) -> T {
            let mut p = self.id.clone();
            let mut q = self.id.clone();
            l += self.n;
            r += self.n;
            while l < r {
                if (l & 1) == 1 {
                    p = (self.op)(p, self.a[l].clone());
                    l += 1;
                }
                if (r & 1) == 1 {
                    r -= 1;
                    q = (self.op)(self.a[r].clone(), q);
                }
                l >>= 1;
                r >>= 1;
            }
            (self.op)(p, q)
        }
    }
}
//---------- end SegmentTree Point update Range query ----------
//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

//

use std::io::Write;

fn euler_tour(v: usize, p: usize, d: u32, g: &Vec<Vec<(usize, usize, u32)>>, l: &mut [usize], r: &mut [usize], ini: &mut Vec<(u32, usize)>) {
    let k = ini.len();
    l[v] = k;
    r[v] = k;
    ini.push((d, v));
    for &(u, _, _) in &g[v] {
        if u == p {
            continue;
        }
        euler_tour(u, v, d + 1, g, l, r, ini);
        ini.push((d, v));
    }
}

fn dfs(v: usize, p: usize, depth: u32, g: &Vec<Vec<(usize, usize, u32)>>, ask: &Vec<Vec<(usize, u32)>>, sum: &mut [u32], cnt: &mut [u32], memo: &mut std::collections::HashMap<(usize, usize, u32), u32>) {
    for &(x, y) in &ask[v] {
        let ans = depth - sum[x] + cnt[x] * y;
        memo.insert((v, x, y), ans);
    }
    for &(u, c, d) in &g[v] {
        if u == p {
            continue;
        }
        sum[c] += d;
        cnt[c] += 1;
        dfs(u, v, depth + d, g, ask, sum, cnt, memo);
        sum[c] -= d;
        cnt[c] -= 1;
    }
}

fn run() {
    input! {
        n: usize,
        q: usize,
        e: [(usize1, usize1, usize1, u32); n - 1],
        p: [(usize1, u32, usize1, usize1); q],
    }
    let mut g = vec![vec![]; n];
    for (a, b, c, d) in e {
        g[a].push((b, c, d));
        g[b].push((a, c, d));
    }
    let mut left = vec![0; n];
    let mut right = vec![0; n];
    let mut ini = vec![];
    euler_tour(0, 0, 0, &g, &mut left, &mut right, &mut ini);
    let mut s = segment_tree::PURQ::new(ini.len(), (1_000_000, 0), std::cmp::min);
    for (i, p) in ini.iter().enumerate() {
        s.update_tmp(i, *p);
    }
    s.update_all();
    let mut ask = vec![vec![]; n];
    for &(x, y, u, v) in &p {
        let l = std::cmp::min(left[u], left[v]);
        let r = std::cmp::max(right[u], right[v]) + 1;
        let lca = s.find(l, r).1;
        ask[u].push((x, y));
        ask[v].push((x, y));
        ask[lca].push((x, y));
    }
    let mut memo = std::collections::HashMap::<(usize, usize, u32), u32>::new();
    let mut sum = vec![0; n];
    let mut cnt = vec![0; n];
    dfs(0, 0, 0, &g, &ask, &mut sum, &mut cnt, &mut memo);
    let out = std::io::stdout();
    let mut out = std::io::BufWriter::new(out.lock());
    for (x, y, u, v) in p {
        let l = std::cmp::min(left[u], left[v]);
        let r = std::cmp::max(right[u], right[v]) + 1;
        let lca = s.find(l, r).1;
        let mut ans = *memo.get(&(u, x, y)).unwrap();
        ans += *memo.get(&(v, x, y)).unwrap();
        ans -= 2 * *memo.get(&(lca, x, y)).unwrap();
        writeln!(out, "{}", ans).unwrap();
    }
}

fn main() {
    run();
}