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.42.0) (judge verdict: Accepted)

#![allow(unused_imports)]
#![allow(non_snake_case)]
use std::cmp::*;
use std::collections::*;
use std::io::Write;

#[allow(unused_macros)]
macro_rules! debug {
    ($($e:expr),*) => {
        #[cfg(debug_assertions)]
        $({
            let (e, mut err) = (stringify!($e), std::io::stderr());
            writeln!(err, "{} = {:?}", e, $e).unwrap()
        })*
    };
}

fn dfs(
    cur: usize,
    parent: usize,
    edges: &Vec<Vec<usize>>,
    depth: &mut Vec<i64>,
    cur_depth: i64,
    dist_dict: &HashMap<(usize, usize), i64>,
) {
    depth[cur] = cur_depth;
    for &to in edges[cur].iter().filter(|&&x| x != parent) {
        let dist = dist_dict[&(cur, to)];
        dfs(to, cur, edges, depth, cur_depth + dist, dist_dict);
    }
}

fn dfs2(
    cur: usize,
    parent: usize,
    edges: &Vec<Vec<usize>>,
    answers: &mut Vec<i64>,
    queries: &Vec<Vec<(usize, usize, i64, i64)>>,
    accum_depth: &mut Vec<i64>,
    accum_num: &mut Vec<i64>,
    color_dict: &HashMap<(usize, usize), usize>,
    dist_dict: &HashMap<(usize, usize), i64>,
) {
    for &to in edges[cur].iter().filter(|&&x| x != parent) {
        let c = color_dict[&(cur, to)];
        let d = dist_dict[&(cur, to)];
        accum_depth[c] += d;
        accum_num[c] += 1;
        for &(qi, x, y, coef) in &queries[to] {
            answers[qi] -= coef * accum_depth[x];
            answers[qi] += coef * accum_num[x] * y;
        }

        dfs2(
            to,
            cur,
            edges,
            answers,
            queries,
            accum_depth,
            accum_num,
            color_dict,
            dist_dict,
        );

        accum_depth[c] -= d;
        accum_num[c] -= 1;
    }
}

fn main() {
    let v = read_vec::<usize>();
    let (n, q) = (v[0], v[1]);
    let mut edges = vec![vec![]; n];
    let mut color_dict = HashMap::new();
    let mut dist_dict = HashMap::new();
    for i in 0..n - 1 {
        let v = read_vec::<i64>();
        let (a, b, c, d) = (v[0] as usize - 1, v[1] as usize - 1, v[2] as usize, v[3]);
        edges[a].push(b);
        edges[b].push(a);
        color_dict.insert((a, b), c);
        color_dict.insert((b, a), c);
        dist_dict.insert((a, b), d);
        dist_dict.insert((b, a), d);
    }
    let mut queries = vec![];
    for i in 0..q {
        let v = read_vec::<i64>();
        let (x, y, u, v) = (v[0] as usize, v[1], v[2] as usize - 1, v[3] as usize - 1);
        queries.push((x, y, u, v));
    }

    let mut depth = vec![0; n];
    dfs(0, 0, &edges, &mut depth, 0, &dist_dict);

    let lca = LCA::new(&edges);

    let mut answers = vec![0; q];
    let mut equeries = vec![vec![]; n];
    for i in 0..q {
        let (x, y, u, v) = queries[i];
        let r = lca.lca(u, v);
        answers[i] = depth[u] + depth[v] - 2 * depth[r];

        equeries[u].push((i, x, y, 1));
        equeries[v].push((i, x, y, 1));
        equeries[r].push((i, x, y, -2));
    }

    let mut accum_depth = vec![0; n];
    let mut accum_num = vec![0; n];

    dfs2(
        0,
        0,
        &edges,
        &mut answers,
        &equeries,
        &mut accum_depth,
        &mut accum_num,
        &color_dict,
        &dist_dict,
    );

    for ans in answers {
        println!("{}", ans);
    }
}

struct LCA {
    depth: Vec<usize>,
    parent: Vec<Vec<Option<usize>>>,
    log_v: usize,
}

impl LCA {
    fn new(g: &Vec<Vec<usize>>) -> LCA {
        LCA::with_root(g, 0)
    }

    fn with_root(g: &Vec<Vec<usize>>, root: usize) -> LCA {
        let n = g.len();
        let log_v = (1..).find(|i| 1usize << i > n).unwrap();
        let mut lca = LCA {
            depth: vec![0usize; n],
            parent: vec![vec![None; n]; 20 + 1], // support 2 ^ 20
            log_v: log_v,
        };
        lca.dfs(root, None, 0, &g);
        lca.doubling(g.len());
        lca
    }

    fn doubling(&mut self, n: usize) {
        for k in 0..self.log_v {
            for v in 0..n {
                if let Some(parent_v) = self.parent[k][v] {
                    self.parent[k + 1][v] = self.parent[k][parent_v];
                }
            }
        }
    }

    fn dfs(&mut self, cur: usize, p: Option<usize>, cur_depth: usize, g: &Vec<Vec<usize>>) {
        self.parent[0][cur] = p;
        self.depth[cur] = cur_depth;
        for &to in g[cur].iter() {
            if Some(to) == p {
                continue;
            }
            self.dfs(to, Some(cur), cur_depth + 1, g);
        }
    }

    fn lca(&self, mut u: usize, mut v: usize) -> usize {
        if self.depth[u] > self.depth[v] {
            std::mem::swap(&mut u, &mut v);
        }
        while self.depth[v] != self.depth[u] {
            v = self.parent[(self.depth[v] - self.depth[u]).trailing_zeros() as usize][v].unwrap();
        }
        if u == v {
            return u;
        }
        for k in (0..self.parent.len()).rev() {
            if self.parent[k][u] != self.parent[k][v] {
                u = self.parent[k][u].unwrap();
                v = self.parent[k][v].unwrap();
            }
        }
        self.parent[0][u].unwrap()
    }
}

fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>()
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}