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 C# (Mono 4.6.2.0) (judge verdict: Runtime Error)

#region いつもの
using System;
using System.Collections.Generic;
using System.Linq;
using IEnumerable = System.Collections.IEnumerable;
using IEnumerator = System.Collections.IEnumerator;
using BigInteger = System.Numerics.BigInteger;
using TextReader = System.IO.TextReader;
using static Global;
using static NumGlobal;

static class Global
{
    public static T[] NewArray<T>(int len0, T value) => new T[len0].Fill(value);
    public static T[] NewArray<T>(int len0, Func<T> factory)
    {
        var arr = new T[len0];
        for (int i = 0; i < arr.Length; i++) arr[i] = factory();
        return arr;
    }
    public static T[][] NewArray<T>(int len0, int len1, T value) where T : struct
    {
        var arr = new T[len0][];
        for (int i = 0; i < arr.Length; i++) arr[i] = NewArray(len1, value);
        return arr;
    }
    public static T[][] NewArray<T>(int len0, int len1, Func<T> factory)
    {
        var arr = new T[len0][];
        for (int i = 0; i < arr.Length; i++) arr[i] = NewArray(len1, factory);
        return arr;
    }
    public static T[][][] NewArray<T>(int len0, int len1, int len2, T value) where T : struct
    {
        var arr = new T[len0][][];
        for (int i = 0; i < arr.Length; i++) arr[i] = NewArray(len1, len2, value);
        return arr;
    }
    public static T[][][] NewArray<T>(int len0, int len1, int len2, Func<T> factory)
    {
        var arr = new T[len0][][];
        for (int i = 0; i < arr.Length; i++) arr[i] = NewArray(len1, len2, factory);
        return arr;
    }
    public static T[][][][] NewArray<T>(int len0, int len1, int len2, int len3, T value) where T : struct
    {
        var arr = new T[len0][][][];
        for (int i = 0; i < arr.Length; i++) arr[i] = NewArray(len1, len2, len3, value);
        return arr;
    }
    public static T[][][][] NewArray<T>(int len0, int len1, int len2, int len3, Func<T> factory)
    {
        var arr = new T[len0][][][];
        for (int i = 0; i < arr.Length; i++) arr[i] = NewArray(len1, len2, len3, factory);
        return arr;
    }
    private class ComparerReverseImpl<T> : Comparer<T> where T : IComparable<T> { public override int Compare(T y, T x) => x.CompareTo(y); public override bool Equals(object obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); }
    public static IComparer<T> ComparerReverse<T>() where T : IComparable<T> => new ComparerReverseImpl<T>();
    public static string AllLines<T>(IEnumerable<T> source) => string.Join("\n", source);
    public static string AllJoin<T>(IEnumerable<T> source) => string.Join(" ", source);
}
static class NumGlobal
{
    public static int Pow(int x, int y)
    {
        int res = 1;
        for (; y > 0; y >>= 1)
        {
            if ((y & 1) == 1) res *= x;
            x *= x;
        }
        return res;
    }
    public static BigInteger ParseBigInteger(string s)
    {
        // MonoのBigInteger.Parseが遅いので自前実装
        var res = BigInteger.Zero;
        var splited = new string[(s.Length + 7) / 8];
        for (var i = 0; i < splited.Length - 1; i++)
        {
            splited[i] = s.Substring(8 * i, 8);
        }
        splited[splited.Length - 1] = s.Substring(8 * (splited.Length - 1));
        foreach (var sp in splited)
        {
            res *= (int)Math.Pow(10, sp.Length);
            res += int.Parse(sp);
        }
        return res;
    }
    public static int BitCount(int x) { x -= (x >> 1) & 0x55555555; x = (x & 0x33333333) + ((x >> 2) & 0x33333333); x = (x + (x >> 4)) & 0x0f0f0f0f; x += x >> 8; x += x >> 16; return x & 0x3f; }
    public static int BitCount(long x) { x -= (x >> 1) & 0x5555555555555555; x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333); x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f; x += x >> 8; x += x >> 16; x += x >> 32; return (int)(x & 0x0000007f); }
    public static int MSB(int x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return BitCount(x) - 1; }
    public static int MSB(long x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; x |= x >> 32; return BitCount(x) - 1; }
    public static int LSB(int x) { x |= x << 1; x |= x << 2; x |= x << 4; x |= x << 8; x |= x << 16; return 32 - BitCount(x); }
    public static int LSB(long x) { x |= x << 1; x |= x << 2; x |= x << 4; x |= x << 8; x |= x << 16; x |= x << 32; return 64 - BitCount(x); }
}
static class Ext
{
    public static T[] Fill<T>(this T[] arr, T value)
    {
        for (var i = 0; i < arr.Length; i++) arr[i] = value;
        return arr;
    }
    public static T[] Sort<T>(this T[] arr)
    {
        Array.Sort(arr);
        return arr;
    }
    public static string[] Sort(this string[] arr)
    {
        Array.Sort(arr, StringComparer.OrdinalIgnoreCase);
        return arr;
    }
    public static T[] Reverse<T>(this T[] arr)
    {
        Array.Reverse(arr);
        return arr;
    }

    public static Tuple<TSource, TMax> MaxBy<TSource, TMax>
        (this IEnumerable<TSource> source, Func<TSource, TMax> maxBySelector)
        where TMax : IComparable<TMax>
    {
        TMax max;
        TSource maxByItem;

        var e = source.GetEnumerator();
        e.MoveNext();
        maxByItem = e.Current;
        max = maxBySelector(maxByItem);
        while (e.MoveNext())
        {
            var item = e.Current;
            var next = maxBySelector(item);
            if (max.CompareTo(next) < 0)
            {
                max = next;
                maxByItem = item;
            }
        }
        return Tuple.Create(maxByItem, max);
    }
    public static Tuple<TSource, TMin> MinBy<TSource, TMin>
        (this IEnumerable<TSource> source, Func<TSource, TMin> minBySelector)
        where TMin : IComparable<TMin>
    {
        TMin min;
        TSource minByItem;

        var e = source.GetEnumerator();
        e.MoveNext();
        minByItem = e.Current;
        min = minBySelector(minByItem);
        while (e.MoveNext())
        {
            var item = e.Current;
            var next = minBySelector(item);
            if (min.CompareTo(next) > 0)
            {
                min = next;
                minByItem = item;
            }
        }
        return Tuple.Create(minByItem, min);
    }
    public static IComparer<T> Reverse<T>(this IComparer<T> comparer) => Comparer<T>.Create((x, y) => comparer.Compare(y, x));
    public static Dictionary<TKey, int> GroupCount<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) => source.GroupBy(keySelector).ToDictionary(g => g.Key, g => g.Count());
    public static Dictionary<TKey, int> GroupCount<TKey>(this IEnumerable<TKey> source) => source.GroupCount(i => i);
}
#pragma warning disable CA1819
[System.Diagnostics.DebuggerNonUserCode]
public class ConsoleReader { private string[] ReadLineSplit() => textReader.ReadLine().Split(Array.Empty<char>(), StringSplitOptions.RemoveEmptyEntries); private string[] line = Array.Empty<string>(); private int linePosition; private TextReader textReader; public ConsoleReader(TextReader tr) { textReader = tr; } public int Int => int.Parse(String); public int Int0 => Int - 1; public long Long => long.Parse(String); public double Double => double.Parse(String); public string String { get { if (linePosition >= line.Length) { linePosition = 0; line = ReadLineSplit(); } return line[linePosition++]; } } public class SplitLine { public SplitLine(ConsoleReader cr) { String = cr.ReadLineSplit(); cr.line = Array.Empty<string>(); } public int[] Int => String.Select(x => int.Parse(x)).ToArray(); public int[] Int0 => String.Select(x => int.Parse(x) - 1).ToArray(); public long[] Long => String.Select(x => long.Parse(x)).ToArray(); public double[] Double => String.Select(x => double.Parse(x)).ToArray(); public string[] String { get; } } public SplitLine Split => new SplitLine(this); public class RepeatReader { ConsoleReader cr; int count; public RepeatReader(ConsoleReader cr, int count) { this.cr = cr; this.count = count; } public T[] Select<T>(Func<ConsoleReader, T> factory) { var arr = new T[count]; for (int i = 0; i < count; i++) arr[i] = factory(cr); return arr; } public string[] String => this.Select(cr => cr.String); public int[] Int => this.Select(cr => cr.Int); public int[] Int0 => this.Select(cr => cr.Int - 1); public long[] Long => this.Select(cr => cr.Long); public double[] Double => this.Select(cr => cr.Double); } public RepeatReader Repeat(int count) => new RepeatReader(this, count); }
public class Program
{
    [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] private ConsoleReader cr;

    public Program(ConsoleReader consoleReader) { this.cr = consoleReader; }
    static void Main() => Console.WriteLine(new Program(new ConsoleReader(Console.In)).Calc());

    #endregion
    public object Calc()
    {
        cr = new ConsoleReader(new System.IO.StreamReader(@"Z:\Downloads\b12.txt"));
        var N = cr.Int;
        var Q = cr.Int;
        var tree = new GraphBuilder(N, cr, N - 1, false).ToTree(0);

        var lca = new LowestCommonAncestor(tree);
        long[] res = new long[Q];

        var clc = new Clc(tree);


        for (int q = 0; q < Q; q++)
        {
            var c = cr.Int0;
            var y = cr.Long;
            var u = cr.Int0;
            var v = cr.Int0;

            var a = lca.Lca(u, v);

            var ut = clc.Get(c, u);
            var vt = clc.Get(c, v);
            var at = clc.Get(c, a);

            res[q] = tree[u].depthLength + tree[v].depthLength - 2 * tree[a].depthLength;
            res[q] -= ut.Item2 + vt.Item2 - 2 * at.Item2;
            res[q] += y * (ut.Item1 + vt.Item1 - 2 * at.Item1);
        }

        return AllLines(res);
    }
}
class Clc : IComparer<int>
{
    TreeNode[] tree;
    public int[] order;
    public int[] dorder;
    public List<int>[] indexes;
    public List<int>[] colorCounts;
    public List<long>[] lengthes;


    public int Compare(int x, int y) => order[x].CompareTo(order[y]);

    public Clc(TreeNode[] tree)
    {
        this.tree = tree;
        order = new int[tree.Length];
        dorder = new int[tree.Length];
        indexes = NewArray(order.Length - 1, () => new List<int>());
        colorCounts = NewArray(order.Length - 1, () => new List<int>());
        lengthes = NewArray(order.Length - 1, () => new List<long>());

        curCounts = new int[tree.Length - 1];
        curLength = new long[tree.Length - 1];

        Init(0);
    }

    public Tuple<int, long> Get(int color, int index)
    {
        var indexes = this.indexes[color];
        var colorCount = colorCounts[color];
        var length = lengthes[color];

        if (indexes.Count == 0)
            return Tuple.Create(0, 0L);

        var i = LowerBound(indexes, index, this);
        if (i >= indexes.Count)
            return Tuple.Create(0, 0L);
        return Tuple.Create(colorCount[i], length[i]);
    }

    private int cursor = 0;
    private int[] curCounts;
    private long[] curLength;
    private void Init(int index)
    {
        dorder[cursor] = index;
        order[index] = cursor++;
        var color = tree[index].color;
        if (color >= 0)
        {
            if (indexes[color].Count == 0 || indexes[color][indexes[color].Count - 1] != dorder[cursor - 2])
            {
                indexes[color].Add(dorder[cursor - 2]);
                colorCounts[color].Add(curCounts[color]);
                lengthes[color].Add(curLength[color]);
            }
            curCounts[color]++;
            curLength[color] += tree[index].depthLength - tree[tree[index].root].depthLength;
        }

        foreach (var next in tree[index].children)
        {
            Init(next.to);
        }

        if (color >= 0)
        {
            indexes[color].Add(dorder[cursor - 1]);
            colorCounts[color].Add(curCounts[color]);
            lengthes[color].Add(curLength[color]);

            curCounts[color]--;
            curLength[color] -= tree[index].depthLength - tree[tree[index].root].depthLength;
        }
    }


    static int BinarySearch<T>(IList<T> a, T v, IComparer<T> cmp, bool isLowerBound)
    {
        var l = 0;
        var r = a.Count - 1;
        while (l <= r)
        {
            var m = (l + r) >> 1;
            var res = cmp.Compare(a[m], v);
            if (res < 0 || (res == 0 && !isLowerBound)) l = m + 1;
            else r = m - 1;
        }
        return l;
    }

    /// <summary>
    /// 与えられた比較関数に従って，<paramref name="a"/> の要素のうち，<paramref name="v"/> 以上の要素であるような最小のインデックスを取得します．
    /// </summary>
    /// <typeparam name="T"><see cref="IList{T}"/> の要素の型を指定します．</typeparam>
    /// <param name="a">対象となるコレクション</param>
    /// <param name="v">対象となる要素</param>
    /// <param name="f"></param>
    /// <returns><paramref name="v"/> 以上の要素であるような最小の o-indexed でのインデックス．</returns>
    /// <remarks> <paramref name="a"/> は比較関数に対して昇順であることを仮定しています．この関数は O(log N) で実行されます．</remarks>
    public static int LowerBound<T>(IList<T> a, T v, IComparer<T> cmp) => BinarySearch(a, v, cmp, true);

}
class GraphBuilder
{
    private List<Next>[] roots;
    private List<Next>[] children;
    public GraphBuilder(int count, bool isOriented = true)
    {
        this.roots = new List<Next>[count];
        this.children = new List<Next>[count];
        for (var i = 0; i < count; i++)
        {
            if (isOriented)
            {
                this.roots[i] = new List<Next>();
                this.children[i] = new List<Next>();
            }
            else
            {
                this.roots[i] = this.children[i] = new List<Next>();
            }
        }
    }
    public GraphBuilder(int count, ConsoleReader cr, int edgeCount, bool isOriented = true) : this(count, isOriented)
    {
        for (var i = 0; i < edgeCount; i++)
            this.Add(cr.Int - 1, cr.Int - 1, cr.Int - 1, cr.Int);
    }
    public void Add(int from, int to, int color, int length)
    {
        children[from].Add(new Next { to = to, color = color, length = length });
        roots[to].Add(new Next { to = from, color = color, length = length });
    }
    public Node[] ToArray() =>
        Enumerable
        .Zip(roots, children, (r, c) => Tuple.Create(r, c))
        .Select((t, i) => new Node(i, t.Item1.ToArray(), t.Item2.ToArray()))
        .ToArray();
    public TreeNode[] ToTree(int root)
    {
        if (this.roots[0] != this.children[0]) throw new Exception("木には無向グラフをしたほうが良い");
        var res = new TreeNode[this.children.Length];
        res[root] = new TreeNode(root, -1, 0, 0, -1, this.children[root].ToArray());

        var queue = new Queue<int>();
        foreach (var child in res[root].children)
        {
            res[child.to] = new TreeNode(child.to, root, 1, child.length, child.color, Array.Empty<Next>());
            queue.Enqueue(child.to);
        }

        while (queue.Count > 0)
        {
            var from = queue.Dequeue();
            if (res[from].root == -1)
                res[from].children = this.children[from].ToArray();
            else
            {
                var children = new List<Next>(this.children[from].Count);
                foreach (var c in this.children[from])
                    if (c.to != res[from].root)
                        children.Add(c);

                res[from].children = children.ToArray();
            }

            foreach (var child in res[from].children)
            {
                res[child.to] = new TreeNode(child.to, from, res[from].depth + 1, res[from].depthLength + child.length, child.color, Array.Empty<Next>());
                queue.Enqueue(child.to);
            }
        }

        return res;
    }
}
public struct Next
{
    public int color;
    public int to;
    public int length;
    public override string ToString() => $"to: {to} length:{length}";
}
class TreeNode
{
    public TreeNode(int i, int root, int depth, long depthLength, int color, Next[] children)
    {
        this.index = i;
        this.root = root;
        this.children = children;
        this.depth = depth;
        this.depthLength = depthLength;
        this.color = color;
    }
    public readonly int index;
    public readonly int root;
    public readonly int depth;
    public readonly long depthLength;
    public readonly int color;
    public Next[] children;

    public override string ToString() => $"children: {string.Join(",", children)}";
    public override bool Equals(object obj)
    {
        if (obj is TreeNode)
            return this.Equals((TreeNode)obj);
        else
            return false;
    }
    public bool Equals(TreeNode other) => this.index == other.index;
    public override int GetHashCode() => this.index;
}
public class Node
{
    public Node(int i, Next[] roots, Next[] children)
    {
        this.index = i;
        this.roots = roots;
        this.children = children;
    }
    public int index;
    public Next[] roots;
    public Next[] children;

    public override bool Equals(object obj)
    {
        if (obj is Node)
            return this.Equals((Node)obj);
        else
            return false;
    }
    public bool Equals(Node other) => this.index == other.index;
    public override int GetHashCode() => this.index;
    public override string ToString() => $"children: ({string.Join("),(", children)})";
}
class LowestCommonAncestor // 最小共通祖先
{
    private TreeNode[] tree;

    // kprv[u][k] 頂点uの2^k個上の祖先頂点v, 0<=k<logN
    private int[][] kprv;
    private int logN;
    public LowestCommonAncestor(TreeNode[] tree)
    {
        if (tree.Length == 0) throw new ArgumentException(nameof(tree));

        this.tree = tree;
        this.logN = (int)(Math.Log(tree.Length, 2) + 1);
        this.kprv = NewArray(tree.Length, logN, 0);
        for (int v = 0; v < tree.Length; v++)
        {
            this.kprv[v][0] = tree[v].root;
        }
        for (int k = 0; k < logN - 1; k++)
        {
            for (int v = 0; v < tree.Length; v++)
            {
                if (this.kprv[v][k] < 0)
                    this.kprv[v][k + 1] = -1;
                else
                    this.kprv[v][k + 1] = this.kprv[this.kprv[v][k]][k];
            }
        }
    }

    public int Lca(int u, int v)
    {
        if (Depth(u) > Depth(v))
        {
            var tmp = u;
            u = v;
            v = tmp;
        }
        for (int k = 0; k <= logN; k++)
        {
            if ((((Depth(v) - Depth(u)) >> k) & 1) == 1)
            {
                v = kprv[v][k];
            }
        }
        if (u == v)
            return u;

        for (int k = logN - 1; k >= 0; k--)
        {
            if (kprv[u][k] != kprv[v][k] && kprv[u][k] != -1 && kprv[v][k] != -1)
            {
                u = kprv[u][k];
                v = kprv[v][k];
            }
        }
        return kprv[u][0];
    }

    int Depth(int index) => tree[index].depth;
}