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)

use std::fmt;
use std::fmt::Debug;
use std::fmt::Display;
use std::rc::Rc;

macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

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

macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

const NODE_SIZE: usize = 4;

#[derive(Debug, Clone)]
struct PersistentArray<T: Clone + Debug> {
    node: Rc<Option<PANode<T>>>,
    size: usize,
}

#[derive(Debug, Clone)]
struct PANode<T: Clone + Debug> {
    data: T,
    nodes: Vec<Rc<Option<PANode<T>>>>,
}

#[allow(dead_code)]
impl<T: Clone + Debug> PersistentArray<T> {
    fn new(v: &[T]) -> PersistentArray<T> {
        let mut node = None;
        for i in 0..v.len() {
            PersistentArray::build(&mut node, i, v[i].clone())
        }
        PersistentArray {
            node: Rc::new(node),
            size: v.len(),
        }
    }
    fn get(&self, i: usize) -> &T {
        PersistentArray::node_get(&self.node, i)
    }
    fn node_get(node: &Option<PANode<T>>, i: usize) -> &T {
        let n = &node.as_ref().unwrap();
        if i == 0 {
            return &n.data;
        }
        PersistentArray::node_get(&n.nodes[(i - 1) % NODE_SIZE], (i - 1) / NODE_SIZE)
    }
    fn set(&self, i: usize, x: T) -> PersistentArray<T> {
        PersistentArray {
            node: PersistentArray::node_set(&self.node, i, x),
            size: self.size,
        }
    }
    fn node_set(node: &Option<PANode<T>>, i: usize, x: T) -> Rc<Option<PANode<T>>> {
        let node = node.as_ref().unwrap();
        if i == 0 {
            return Rc::new(Some(PANode {
                data: x,
                nodes: node.nodes.clone(),
            }));
        }
        let mut nodes = node.nodes.clone();
        nodes[(i - 1) % NODE_SIZE] =
            PersistentArray::node_set(&nodes[(i - 1) % NODE_SIZE], (i - 1) / NODE_SIZE, x);
        Rc::new(Some(PANode {
            data: node.data.clone(),
            nodes,
        }))
    }
    fn build(node: &mut Option<PANode<T>>, i: usize, x: T) {
        match node {
            None => {
                let mut nodes = Vec::with_capacity(NODE_SIZE);
                for _ in 0..NODE_SIZE {
                    nodes.push(Rc::new(None))
                }
                *node = Some(PANode { data: x, nodes });
            }
            Some(ref mut n) => {
                if i == 0 {
                    n.data = x;
                } else {
                    PersistentArray::build(
                        Rc::get_mut(&mut n.nodes[(i - 1) % NODE_SIZE]).unwrap(),
                        (i - 1) / NODE_SIZE,
                        x,
                    )
                }
            }
        }
    }
    fn to_vec(&self) -> Vec<T> {
        let mut res = vec![];
        let mut stack = vec![];
        stack.push(&self.node);
        while let Some(node) = stack.pop() {
            match node.as_ref() {
                &None => continue,
                Some(node) => {
                    res.push(node.data.clone());
                    for i in 0..NODE_SIZE {
                        stack.insert(0, &node.nodes[i])
                    }
                }
            }
        }
        return res;
    }
}
impl<T: Clone + Debug> Display for PersistentArray<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "PersistentArray {:?}", self.to_vec())
    }
}

use std::collections::HashMap;
#[derive(Clone)]
struct VGraph<T: Clone + Debug> {
    edges: Vec<HashMap<usize, T>>,
    size: usize,
    plus: fn(&T, &T) -> T,
    zero: T,
}
type VG = VGraph<usize>;

#[allow(dead_code)]
impl<T: Clone + Debug> VGraph<T> {
    fn new_int(size: usize, edges: &[(usize, usize)]) -> VG {
        let edges: Vec<(usize, usize, usize)> = edges.iter().map(|&(x, y)| (x, y, 1)).collect();
        VGraph::new(size, &edges, 0, |x, y| x + y)
    }
    fn new_int_directed(size: usize, edges: &[(usize, usize)]) -> VG {
        let edges: Vec<(usize, usize, usize)> = edges.iter().map(|&(x, y)| (x, y, 1)).collect();
        VGraph::new_directed(size, &edges, 0, |x, y| x + y)
    }
    fn new(size: usize, edges: &[(usize, usize, T)], zero: T, plus: fn(&T, &T) -> T) -> VGraph<T> {
        let mut res = Vec::with_capacity(size);
        for _ in 0..size {
            res.push(HashMap::new())
        }
        for &(s, t, ref d) in edges {
            res[s].insert(t, d.clone());
            res[t].insert(s, d.clone());
        }
        VGraph {
            edges: res,
            size,
            plus,
            zero,
        }
    }
    fn new_directed(
        size: usize,
        edges: &[(usize, usize, T)],
        zero: T,
        plus: fn(&T, &T) -> T,
    ) -> VGraph<T> {
        let mut res = Vec::with_capacity(size);
        for _ in 0..size {
            res.push(HashMap::new())
        }
        for &(s, t, ref d) in edges {
            res[s].insert(t, d.clone());
        }
        VGraph {
            edges: res,
            size,
            zero,
            plus,
        }
    }
    /// (Parent, Len, Distance) from root
    fn dfs(&self, root: usize) -> (Vec<usize>, Vec<usize>, Vec<T>) {
        let mut dist = Vec::with_capacity(self.size);
        for _ in 0..self.size {
            dist.push(self.zero.clone());
        }
        let mut parent = vec![0; self.size];
        let mut len = vec![0; self.size];
        let mut stack = vec![(root, 0, self.zero.clone())];
        let mut visited = vec![false; self.size];
        visited[root] = true;
        dist[root] = self.zero.clone();
        len[root] = 0;
        parent[root] = self.size;
        while let Some((node, l, d)) = stack.pop() {
            for (&to, cost) in &self.edges[node] {
                if visited[to] {
                    continue;
                }
                visited[to] = true;
                let nd = (self.plus)(&d, cost);
                let nl = l + 1;
                dist[to] = nd.clone();
                parent[to] = node;
                len[to] = nl;
                stack.push((to, nl, nd));
            }
        }
        (parent, len, dist)
    }
}
impl<T: Clone + Debug> fmt::Debug for VGraph<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "VGraph {:?}", self.edges)
    }
}

#[allow(dead_code)]
#[derive(Clone, Debug)]
struct LCA<T: Clone + Debug> {
    graph: VGraph<T>,
    root: usize,
    parents: Vec<Vec<usize>>,
    len: Vec<usize>,
    dist: Vec<T>,
}
#[allow(dead_code)]
impl<T: Clone + Debug> LCA<T> {
    fn new(root: usize, graph: VGraph<T>) -> LCA<T> {
        let (parent, len, dist) = graph.dfs(root);
        let mut k = 1;
        while (1 << k) < graph.size {
            k += 1;
        }
        let mut parents = vec![vec![42; graph.size]; k];
        for i in 0..graph.size {
            parents[0][i] = parent[i];
        }
        for i in 0..k - 1 {
            for v in 0..graph.size {
                if parents[i][v] >= graph.size {
                    parents[i + 1][v] = graph.size;
                } else {
                    parents[i + 1][v] = parents[i][parents[i][v]]
                }
            }
        }
        LCA {
            graph,
            root,
            len,
            parents,
            dist,
        }
    }
    fn lca(&self, x: usize, y: usize) -> usize {
        let mut x = x;
        let mut y = y;
        if self.len[x] < self.len[y] {
            let t = x;
            x = y;
            y = t;
        }
        let k = self.parents.len();
        for i in 0..k {
            if ((self.len[x] - self.len[y]) >> i) & 1 == 1 {
                x = self.parents[i][x];
            }
        }
        if x == y {
            return x;
        }
        for i in 0..k {
            let i = k - i - 1;
            if self.parents[i][x] != self.parents[i][y] {
                x = self.parents[i][x];
                y = self.parents[i][y];
            }
        }
        return self.parents[0][x];
    }
    fn dist_xy(&self, x: usize, y: usize, minus: fn(&T, &T) -> T) -> T {
        let p = self.lca(x, y);
        let xy = (self.graph.plus)(&self.dist[x], &self.dist[y]);
        let dp = &self.dist[p];
        (minus)(&(minus)(&xy, dp), dp)
    }
    fn len_xy(&self, x: usize, y: usize) -> usize {
        let p = self.lca(x, y);
        let xy = self.len[x] + self.len[y];
        let dp = self.len[p];
        xy - 2 * dp
    }
    fn on_xy(&self, x: usize, y: usize, a: usize) -> bool {
        self.len_xy(x, a) + self.len_xy(a, y) == self.len_xy(x, y)
    }
}

fn main() {
    input! {
        n : usize, q : usize,
        abcd: [(usize1, usize1, usize1, usize); n-1],
        xyuv: [(usize1, usize, usize1, usize1); q]
    }
    let mut gv = Vec::with_capacity(n);
    for (a, b, c, d) in abcd {
        gv.push((a, b, (c, d)))
    }
    let g = VGraph::new(n, &gv, (0, 0), |&(_, x), &(_, y)| (0, x + y));
    let lca = LCA::new(0, g.clone());
    let cd = PersistentArray::new(&vec![0; n]);
    let cn = PersistentArray::new(&vec![0; n]);
    let mut color_d = Vec::with_capacity(n);
    let mut color_n = Vec::with_capacity(n);
    for _ in 0..n {
        color_d.push(cd.clone());
        color_n.push(cn.clone());
    }

    fn dfs(
        prev: usize,
        now: usize,
        color_d: &mut Vec<PersistentArray<usize>>,
        color_n: &mut Vec<PersistentArray<usize>>,
        g: &VGraph<(usize, usize)>,
    ) {
        for (&t, &(c, d)) in &g.edges[now] {
            if t == prev {
                continue;
            }
            color_d[t] = color_d[now].set(c, color_d[now].get(c) + d);
            color_n[t] = color_n[now].set(c, color_n[now].get(c) + 1);
            dfs(now, t, color_d, color_n, g);
        }
    }
    dfs(n, 0, &mut color_d, &mut color_n, &g);

    for (x, d, u, v) in xyuv {
        let p = lca.lca(u, v);
        let (_, l) = lca.dist_xy(u, v, |&(_, x), &(_, y)| (0, x - y));
        let du = color_d[u].get(x);
        let dv = color_d[v].get(x);
        let dp = color_d[p].get(x);
        let nu = color_n[u].get(x);
        let nv = color_n[v].get(x);
        let np = color_n[p].get(x);
        let path_d = du + dv - 2 * dp;
        let path_n = nu + nv - 2 * np;
        let res = l - path_d + d * path_n;
        println!("{}", res)
    }
}