Problem:
Score : 600 points

Problem Statement

We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i.
Vertex i has an integer a_i written on it.
For every integer k from 1 through N, solve the following problem:

We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k, in the order they appear. Find the length of the longest increasing subsequence of this sequence.

Here, the longest increasing subsequence of a sequence A of length L is the subsequence A_{i_1} , A_{i_2} , ... , A_{i_M} with the greatest possible value of M such that 1 \leq i_1 < i_2 < ... < i_M \leq L and A_{i_1} < A_{i_2} < ... < A_{i_M}.

Constraints

2 \leq N \leq 2 \times 10^5

1 \leq a_i \leq 10^9

1 \leq u_i , v_i \leq N

u_i \neq v_i

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}

Output

Print N lines. The k-th line, print the length of the longest increasing subsequence of the sequence obtained from the shortest path from Vertex 1 to Vertex k.

Sample Input 1

10
1 2 5 3 4 6 7 3 2 4
1 2
2 3
3 4
4 5
3 6
6 7
1 8
8 9
9 10

Sample Output 1

1
2
3
3
4
4
5
2
2
3

For example, the sequence A obtained from the shortest path from Vertex 1 to Vertex 5 is 1,2,5,3,4. Its longest increasing subsequence is A_1, A_2, A_4, A_5, with the length of 4.

Solution in C# (Mono-mcs 6.8.0.105) (judge verdict: Wrong Answer)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using static System.Math;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Runtime.CompilerServices;
using Library;

namespace Program
{
    public static class ABC165F
    {
        static bool SAIKI = false;
        static public int numberOfRandomCases = 0;
        static public void MakeTestCase(List<string> _input, List<string> _output, ref Func<string[], bool> _outputChecker)
        {
        }
        static public void Solve()
        {
            var N = NN;
            var aList = NNList(N);
            var uv = Repeat(0, N - 1).Select(_ => new { u = NN - 1, v = NN - 1 }).ToArray();
            var tree = new LIB_Tree(N);
            foreach (var item in uv)
            {
                tree.AddPath(item.u, item.v);
            }
            var tre = new LIB_RedBlackTree<long>();
            var tre2 = new LIB_RedBlackTree<long>();
            var geta = 1000000L;
            var ans2 = new long[N];
            var ans = new long[N];
            foreach (var item in tree.EulerTour(0))
            {
                if (item.direction == 1)
                {
                    var idx = tre.LowerBound(aList[item.node] * geta);
                    if (idx == 0)
                    {
                        tre.Add(aList[item.node] * geta + 1);
                        tre2.Add(1);
                        ans2[item.node] = 1;
                    }
                    else
                    {
                        var val = tre[idx - 1];
                        var cnt = val % geta;
                        ++cnt;
                        tre.Add(aList[item.node] * geta + cnt);
                        tre2.Add(cnt);
                        ans2[item.node] = cnt;
                    }
                    ans[item.node] = tre2.Max();
                }
                else
                {
                    tre.Remove(aList[item.node] * geta + ans2[item.node]);
                    tre2.Remove(ans2[item.node]);
                }
            }
            foreach (var item in ans)
            {
                Console.WriteLine(item);
            }
        }
        class Printer : StreamWriter
        {
            public override IFormatProvider FormatProvider { get { return CultureInfo.InvariantCulture; } }
            public Printer(Stream stream) : base(stream, new UTF8Encoding(false, true)) { base.AutoFlush = false; }
            public Printer(Stream stream, Encoding encoding) : base(stream, encoding) { base.AutoFlush = false; }
        }
        static LIB_FastIO fastio = new LIB_FastIODebug();
        static public void Main(string[] args) { if (args.Length == 0) { fastio = new LIB_FastIO(); Console.SetOut(new Printer(Console.OpenStandardOutput())); } if (SAIKI) { var t = new Thread(Solve, 134217728); t.Start(); t.Join(); } else Solve(); Console.Out.Flush(); }
        static long NN => fastio.Long();
        static double ND => fastio.Double();
        static string NS => fastio.Scan();
        static long[] NNList(long N) => Repeat(0, N).Select(_ => NN).ToArray();
        static double[] NDList(long N) => Repeat(0, N).Select(_ => ND).ToArray();
        static string[] NSList(long N) => Repeat(0, N).Select(_ => NS).ToArray();
        static long Count<T>(this IEnumerable<T> x, Func<T, bool> pred) => Enumerable.Count(x, pred);
        static IEnumerable<T> Repeat<T>(T v, long n) => Enumerable.Repeat<T>(v, (int)n);
        static IEnumerable<int> Range(long s, long c) => Enumerable.Range((int)s, (int)c);
        static IOrderedEnumerable<T> OrderByRand<T>(this IEnumerable<T> x) => Enumerable.OrderBy(x, _ => xorshift);
        static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> x) => Enumerable.OrderBy(x.OrderByRand(), e => e);
        static IOrderedEnumerable<T1> OrderBy<T1, T2>(this IEnumerable<T1> x, Func<T1, T2> selector) => Enumerable.OrderBy(x.OrderByRand(), selector);
        static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> x) => Enumerable.OrderByDescending(x.OrderByRand(), e => e);
        static IOrderedEnumerable<T1> OrderByDescending<T1, T2>(this IEnumerable<T1> x, Func<T1, T2> selector) => Enumerable.OrderByDescending(x.OrderByRand(), selector);
        static IOrderedEnumerable<string> OrderBy(this IEnumerable<string> x) => x.OrderByRand().OrderBy(e => e, StringComparer.OrdinalIgnoreCase);
        static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> x, Func<T, string> selector) => x.OrderByRand().OrderBy(selector, StringComparer.OrdinalIgnoreCase);
        static IOrderedEnumerable<string> OrderByDescending(this IEnumerable<string> x) => x.OrderByRand().OrderByDescending(e => e, StringComparer.OrdinalIgnoreCase);
        static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> x, Func<T, string> selector) => x.OrderByRand().OrderByDescending(selector, StringComparer.OrdinalIgnoreCase);
        static uint xorshift { get { _xsi.MoveNext(); return _xsi.Current; } }
        static IEnumerator<uint> _xsi = _xsc();
        static IEnumerator<uint> _xsc() { uint x = 123456789, y = 362436069, z = 521288629, w = (uint)(DateTime.Now.Ticks & 0xffffffff); while (true) { var t = x ^ (x << 11); x = y; y = z; z = w; w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)); yield return w; } }
    }
}
namespace Library {
    class LIB_RedBlackTree
    {
        public struct SumEntity
        {
            public long s;
            public long c;
        }
        static public LIB_RedBlackTree<long, long, long> CreateRUQRmQ() => new LIB_RedBlackTree<long, long, long>(long.MaxValue, long.MaxValue, Math.Min, (x, y) => y, (x, y) => y);
        static public LIB_RedBlackTree<long, long, long> CreateRAQRmQ() => new LIB_RedBlackTree<long, long, long>(long.MaxValue, 0, Math.Min, (x, y) => x + y, (x, y) => x + y);
        static public LIB_RedBlackTree<long, long, long> CreateRUQRMQ() => new LIB_RedBlackTree<long, long, long>(long.MinValue, long.MinValue, Math.Max, (x, y) => y, (x, y) => y);
        static public LIB_RedBlackTree<long, long, long> CreateRAQRMQ() => new LIB_RedBlackTree<long, long, long>(long.MinValue, 0, Math.Max, (x, y) => x + y, (x, y) => x + y);
        static public LIB_RedBlackTree<long, SumEntity, long> CreateRUQRSQ() => new LIB_RedBlackTree<long, SumEntity, long>(new SumEntity { c = 0, s = 0 }, long.MaxValue, (x, y) => new SumEntity { c = x.c + y.c, s = x.s + y.s }, (x, y) => new SumEntity { c = x.c, s = x.c * y }, (x, y) => y);
        static public LIB_RedBlackTree<long, SumEntity, long> CreateRAQRSQ() => new LIB_RedBlackTree<long, SumEntity, long>(new SumEntity { c = 0, s = 0 }, 0, (x, y) => new SumEntity { c = x.c + y.c, s = x.s + y.s }, (x, y) => new SumEntity { c = x.c, s = x.s + x.c * y }, (x, y) => x + y);
    }
    class LIB_RedBlackTree<Key, ValueT, ValueE> where ValueE : IEquatable<ValueE>
    {
        bool ope;
        class Node
        {
            public Node left;
            public Node right;
            public Key key;
            public ValueT val;
            public ValueT dat;
            public ValueE lazy;
            public bool isBlack;
            public int cnt;
            public bool needRecalc;
        }
        Func<ValueT, ValueT, ValueT> f;
        Func<ValueT, ValueE, ValueT> g;
        Func<ValueE, ValueE, ValueE> h;
        ValueT ti;
        ValueE ei;
        Comparison<Key> c;
        Node root;
        bool isNeedFix;
        Node lmax;
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LIB_RedBlackTree(ValueT ti, ValueE ei, Func<ValueT, ValueT, ValueT> f, Func<ValueT, ValueE, ValueT> g, Func<ValueE, ValueE, ValueE> h, Comparison<Key> c, bool ope = true)
        {
            this.ti = ti;
            this.ei = ei;
            this.f = f;
            this.g = g;
            this.h = h;
            this.c = c;
            this.ope = ope;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LIB_RedBlackTree(ValueT ti, ValueE ei, Func<ValueT, ValueT, ValueT> f, Func<ValueT, ValueE, ValueT> g, Func<ValueE, ValueE, ValueE> h) : this(ti, ei, f, g, h, Comparer<Key>.Default.Compare) { }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        bool IsRed(Node n) => n != null && !n.isBlack;
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        bool IsBlack(Node n) => n != null && n.isBlack;
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        int Cnt(Node n) => n?.cnt ?? 0;
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        void Eval(Node n)
        {
            if (n == null || ei.Equals(n.lazy)) return;
            n.val = g(n.val, n.lazy);
            if (!n.needRecalc) n.dat = g(n.dat, n.lazy);
            if (n.left != null) n.left.lazy = h(n.left.lazy, n.lazy);
            if (n.right != null) n.right.lazy = h(n.right.lazy, n.lazy);
            n.lazy = ei;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        void Recalc(Node n)
        {
            if (n == null) return;
            Eval(n);
            if (!n.needRecalc) return;
            n.needRecalc = false;
            n.dat = n.val;
            if (n.left != null)
            {
                Recalc(n.left);
                n.dat = f(n.left.dat, n.dat);
            }
            if (n.right != null)
            {
                Recalc(n.right);
                n.dat = f(n.dat, n.right.dat);
            }
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        Node RotateL(Node n)
        {
            if (ope) { Eval(n); Eval(n.right); }
            Node m = n.right, t = m.left;
            m.left = n; n.right = t;
            n.cnt -= m.cnt - Cnt(t);
            m.cnt += n.cnt - Cnt(t);
            if (ope) { n.needRecalc = true; m.needRecalc = true; }
            return m;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        Node RotateR(Node n)
        {
            if (ope) { Eval(n); Eval(n.left); }
            Node m = n.left, t = m.right;
            m.right = n; n.left = t;
            n.cnt -= m.cnt - Cnt(t);
            m.cnt += n.cnt - Cnt(t);
            if (ope) { n.needRecalc = true; m.needRecalc = true; }
            return m;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        Node RotateLR(Node n)
        {
            n.left = RotateL(n.left);
            return RotateR(n);
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        Node RotateRL(Node n)
        {
            n.right = RotateR(n.right);
            return RotateL(n);
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Add(Key key, ValueT val)
        {
            root = Add(root, key, val);
            root.isBlack = true;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        Node Add(Node n, Key key, ValueT val)
        {
            if (n == null)
            {
                isNeedFix = true;
                return new Node() { key = key, val = val, dat = val, lazy = ei, cnt = 1 };
            }
            if (ope) Eval(n);
            if (c(key, n.key) < 0) n.left = Add(n.left, key, val);
            else n.right = Add(n.right, key, val);
            if (ope) n.needRecalc = true;
            n.cnt++;
            return Balance(n);
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        Node Balance(Node n)
        {
            if (!isNeedFix) return n;
            if (!IsBlack(n)) return n;
            if (IsRed(n.left) && IsRed(n.left.left))
            {
                n = RotateR(n);
                n.left.isBlack = true;
            }
            else if (IsRed(n.left) && IsRed(n.left.right))
            {
                n = RotateLR(n);
                n.left.isBlack = true;
            }
            else if (IsRed(n.right) && IsRed(n.right.left))
            {
                n = RotateRL(n);
                n.right.isBlack = true;
            }
            else if (IsRed(n.right) && IsRed(n.right.right))
            {
                n = RotateL(n);
                n.right.isBlack = true;
            }
            else isNeedFix = false;
            return n;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Remove(Key key)
        {
            root = Remove(root, key);
            if (root != null) root.isBlack = true;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        Node Remove(Node n, Key key)
        {
            if (n == null) throw new Exception();
            if (ope) Eval(n);
            n.cnt--;
            var r = c(key, n.key);
            if (r < 0)
            {
                n.left = Remove(n.left, key);
                if (ope) n.needRecalc = true;
                return BalanceL(n);
            }
            if (r > 0)
            {
                n.right = Remove(n.right, key);
                if (ope) n.needRecalc = true;
                return BalanceR(n);
            }
            if (n.left == null)
            {
                isNeedFix = n.isBlack;
                return n.right;
            }
            n.left = RemoveMax(n.left);
            n.key = lmax.key;
            n.val = lmax.val;
            if (ope) n.needRecalc = true;
            return BalanceL(n);
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        Node RemoveMax(Node n)
        {
            if (ope) Eval(n);
            n.cnt--;
            if (n.right != null)
            {
                n.right = RemoveMax(n.right);
                if (ope) n.needRecalc = true;
                return BalanceR(n);
            }
            lmax = n;
            isNeedFix = n.isBlack;
            return n.left;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        Node BalanceL(Node n)
        {
            if (!isNeedFix) return n;
            if (IsBlack(n.right) && IsRed(n.right.left))
            {
                var b = n.isBlack;
                n = RotateRL(n);
                n.isBlack = b;
                n.left.isBlack = true;
                isNeedFix = false;
            }
            else if (IsBlack(n.right) && IsRed(n.right.right))
            {
                var b = n.isBlack;
                n = RotateL(n);
                n.isBlack = b;
                n.right.isBlack = true;
                n.left.isBlack = true;
                isNeedFix = false;
            }
            else if (IsBlack(n.right))
            {
                isNeedFix = n.isBlack;
                n.isBlack = true;
                n.right.isBlack = false;
            }
            else
            {
                n = RotateL(n);
                n.isBlack = true;
                n.left.isBlack = false;
                n.left = BalanceL(n.left);
                isNeedFix = false;
            }
            return n;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        Node BalanceR(Node n)
        {
            if (!isNeedFix) return n;
            if (IsBlack(n.left) && IsRed(n.left.right))
            {
                var b = n.isBlack;
                n = RotateLR(n);
                n.isBlack = b; n.right.isBlack = true;
                isNeedFix = false;
            }
            else if (IsBlack(n.left) && IsRed(n.left.left))
            {
                var b = n.isBlack;
                n = RotateR(n);
                n.isBlack = b;
                n.left.isBlack = true;
                n.right.isBlack = true;
                isNeedFix = false;
            }
            else if (IsBlack(n.left))
            {
                isNeedFix = n.isBlack;
                n.isBlack = true;
                n.left.isBlack = false;
            }
            else
            {
                n = RotateR(n);
                n.isBlack = true;
                n.right.isBlack = false;
                n.right = BalanceR(n.right);
                isNeedFix = false;
            }
            return n;
        }
        public KeyValuePair<Key, ValueT> this[long i]
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get { return At(root, i); }
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        KeyValuePair<Key, ValueT> At(Node n, long i)
        {
            if (ope) Eval(n);
            if (n.left == null)
            {
                if (i == 0) return new KeyValuePair<Key, ValueT>(n.key, n.val);
                else return At(n.right, i - 1);
            }
            if (n.left.cnt == i) return new KeyValuePair<Key, ValueT>(n.key, n.val);
            if (n.left.cnt > i) return At(n.left, i);
            return At(n.right, i - n.left.cnt - 1);
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool Have(Key key)
        {
            var t = LowerBound(key);
            return t < Cnt(root) && c(At(root, t).Key, key) == 0;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public long UpperBound(Key key) => UpperBound(root, key);
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        long UpperBound(Node n, Key key)
        {
            if (n == null) return 0;
            var r = c(key, n.key);
            if (r < 0) return UpperBound(n.left, key);
            return Cnt(n.left) + 1 + UpperBound(n.right, key);
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public long LowerBound(Key key) => LowerBound(root, key);
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        long LowerBound(Node n, Key key)
        {
            if (n == null) return 0;
            var r = c(key, n.key);
            if (r <= 0) return LowerBound(n.left, key);
            return Cnt(n.left) + 1 + LowerBound(n.right, key);
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public KeyValuePair<Key, ValueT> Min()
        {
            Node n = root.left, p = root;
            while (n != null)
            {
                p = n;
                if (ope) Eval(p);
                n = n.left;
            }
            return new KeyValuePair<Key, ValueT>(p.key, p.val);
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public KeyValuePair<Key, ValueT> Max()
        {
            Node n = root.right, p = root;
            while (n != null)
            {
                p = n;
                if (ope) Eval(p);
                n = n.right;
            }
            return new KeyValuePair<Key, ValueT>(p.key, p.val);
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Update(long l, long r, ValueE val) => Update(root, l, r, val);
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        void Update(Node n, long l, long r, ValueE val)
        {
            if (n == null) return;
            Eval(n);
            n.needRecalc = true;
            var lc = Cnt(n.left);
            if (lc < l) Update(n.right, l - lc - 1, r - lc - 1, val);
            else if (r <= lc) Update(n.left, l, r, val);
            else if (l <= 0 && Cnt(n) <= r) n.lazy = val;
            else
            {
                n.val = g(n.val, val);
                if (l < lc) Update(n.left, l, lc, val);
                if (lc + 1 < r) Update(n.right, 0, r - lc - 1, val);
            }
            return;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public ValueT Query(long l, long r) => Query(root, l, r);
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        ValueT Query(Node n, long l, long r)
        {
            var v1 = ti; var v2 = ti; var v3 = ti;
            if (n == null) return ti;
            Eval(n);
            var lc = Cnt(n.left);
            if (lc < l) v3 = Query(n.right, l - lc - 1, r - lc - 1);
            else if (r <= lc) v1 = Query(n.left, l, r);
            else if (l <= 0 && Cnt(n) <= r)
            {
                Recalc(n);
                v2 = n.dat;
            }
            else
            {
                if (l < lc) v1 = Query(n.left, l, lc);
                if (lc + 1 < r) v3 = Query(n.right, 0, r - lc - 1);
                v2 = n.val;
            }
            return f(f(v1, v2), v3);
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool Any() => root != null;
        public long Count => Cnt(root);
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public IEnumerable<KeyValuePair<Key, ValueT>> List() => L(root);
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        IEnumerable<KeyValuePair<Key, ValueT>> L(Node n)
        {
            if (n == null) yield break;
            foreach (var i in L(n.left)) yield return i;
            yield return new KeyValuePair<Key, ValueT>(n.key, n.val);
            foreach (var i in L(n.right)) yield return i;
        }
    }
    class LIB_RedBlackTree<Key, Value>
    {
        LIB_RedBlackTree<Key, Value, int> tree;
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LIB_RedBlackTree(Comparison<Key> c) { tree = new LIB_RedBlackTree<Key, Value, int>(default(Value), 0, (x, y) => x, (x, y) => x, (x, y) => x, c, false); }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LIB_RedBlackTree() : this(Comparer<Key>.Default.Compare) { }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Add(Key key, Value val) => tree.Add(key, val);
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Remove(Key key) => tree.Remove(key);
        public KeyValuePair<Key, Value> this[long i]
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get { return tree[i]; }
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool Have(Key key) => tree.Have(key);
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public long UpperBound(Key key) => tree.UpperBound(key);
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public long LowerBound(Key key) => tree.LowerBound(key);
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public KeyValuePair<Key, Value> Min() => tree.Min();
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public KeyValuePair<Key, Value> Max() => tree.Max();
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool Any() => tree.Any();
        public long Count => tree.Count;
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public IEnumerable<KeyValuePair<Key, Value>> List() => tree.List();
    }
    class LIB_RedBlackTree<T>
    {
        LIB_RedBlackTree<T, int, int> tree;
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LIB_RedBlackTree(Comparison<T> c) { tree = new LIB_RedBlackTree<T, int, int>(0, 0, (x, y) => x, (x, y) => x, (x, y) => x, c, false); }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LIB_RedBlackTree() : this(Comparer<T>.Default.Compare) { }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Add(T val) => tree.Add(val, 0);
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Remove(T val) => tree.Remove(val);
        public T this[long i]
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get { return tree[i].Key; }
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool Have(T val) => tree.Have(val);
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public long UpperBound(T val) => tree.UpperBound(val);
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public long LowerBound(T val) => tree.LowerBound(val);
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public T Min() => tree.Min().Key;
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public T Max() => tree.Max().Key;
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool Any() => tree.Any();
        public long Count => tree.Count;
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public IEnumerable<T> List() => tree.List().Select(e => e.Key);
    }
    class LIB_Tree
    {
        int N;
        List<int>[] path;
        public struct EulerRes
        {
            public long node;
            public long parent;
            public long direction;
        }
        List<EulerRes> eulerList;
        public struct BFSRes
        {
            public long node;
            public long parent;
        }
        List<BFSRes> bfsList;
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LIB_Tree(long n)
        {
            N = (int)n;
            path = Enumerable.Repeat(0, N).Select(_ => new List<int>()).ToArray();
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void AddPath(long u, long v)
        {
            if (u >= N || v >= N) throw new Exception();
            path[u].Add((int)v);
            path[v].Add((int)u);
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public int[] GetSurround(long u) => path[u].ToArray();
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public List<BFSRes> BFSFromRoot(long root)
        {
            bfsList = new List<BFSRes>();
            var q = new Queue<int>();
            var done = new bool[N];
            bfsList.Add(new BFSRes { node = root, parent = -1 });
            done[root] = true;
            q.Enqueue((int)root);
            while (q.Count > 0)
            {
                var w = q.Dequeue();
                foreach (var i in path[w])
                {
                    if (done[i]) continue;
                    done[i] = true;
                    q.Enqueue(i);
                    bfsList.Add(new BFSRes { node = i, parent = w });
                }
            }
            return bfsList;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public List<BFSRes> BFSFromLeaf(long root) => BFSFromRoot(root).ToArray().Reverse().ToList();
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public List<EulerRes> EulerTour(long root)
        {
            eulerList = new List<EulerRes>();
            var s = new Stack<Tuple<int, int>>();
            var done = new bool[N];
            done[root] = true;
            s.Push(Tuple.Create((int)root, -1));
            while (s.Count > 0)
            {
                var w = s.Peek();
                var ad = true;
                foreach (var i in path[w.Item1])
                {
                    if (done[i]) continue;
                    done[i] = true;
                    ad = false;
                    s.Push(Tuple.Create(i, w.Item1));
                }
                if (!ad || path[w.Item1].Count == 1) eulerList.Add(new EulerRes { node = w.Item1, parent = w.Item2, direction = 1 });
                if (ad)
                {
                    s.Pop();
                    eulerList.Add(new EulerRes { node = w.Item1, parent = w.Item2, direction = -1 });
                }
            }
            return eulerList;
        }
        public class LCAResult
        {
            int[] depth;
            int l;
            int[][] pr;
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public LCAResult(int[] depth, int l, int[][] pr)
            {
                this.depth = depth;
                this.l = l;
                this.pr = pr;
            }
            public long this[long u, long v]
            {
                [MethodImpl(MethodImplOptions.AggressiveInlining)]
                get
                {
                    if (depth[u] > depth[v])
                    {
                        var t = u; u = v; v = t;
                    }
                    for (var k = 0; k < l; k++)
                    {
                        if ((((depth[v] - depth[u]) >> k) & 1) != 0) v = pr[k][v];
                    }
                    if (u == v) return u;
                    for (var k = l - 1; k >= 0; k--)
                    {
                        if (pr[k][u] != pr[k][v])
                        {
                            u = pr[k][u];
                            v = pr[k][v];
                        }
                    }
                    return pr[0][u];
                }
            }
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LCAResult BuildLCA(long root)
        {
            var depth = new int[N];
            var l = 0;
            while (N > (1 << l)) l++;
            var pr = Enumerable.Repeat(0, l).Select(_ => new int[N]).ToArray();
            depth[root] = 0;
            pr[0][root] = -1;
            var q = new Stack<int>();
            q.Push((int)root);
            while (q.Count > 0)
            {
                var w = q.Pop();
                foreach (var i in path[w])
                {
                    if (i == pr[0][w]) continue;
                    q.Push(i);
                    depth[i] = depth[w] + 1;
                    pr[0][i] = w;
                }
            }
            for (var k = 0; k + 1 < l; k++)
            {
                for (var w = 0; w < N; w++)
                {
                    if (pr[k][w] < 0) pr[k + 1][w] = -1;
                    else pr[k + 1][w] = pr[k][pr[k][w]];
                }
            }
            return new LCAResult(depth, l, pr);
        }
        /// <summary>
        /// 蜈ｨ譁ｹ菴肴惠DP
        /// </summary>
        /// <param name="idxToVal">鬆らせ逡ｪ蜿ｷ縺九ｉ蛟､繧貞叙蠕・/param>
        /// <param name="mergeSubTrees">驛ｨ蛻・惠縺ｨ驛ｨ蛻・惠縺ｮ繝槭・繧ｸ (subtree, subtree)</param>
        /// <returns>2谺｡蜈・・蛻夕node, parent]縺ｮ驛ｨ蛻・惠縺ｮDP蛟､縲Ｑarent=-1縺ｯnode繧偵Ν繝ｼ繝医→縺励◆譛ｨ縺ｮ蛟､</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public CReRooting<T> ReRooting<T>(Func<long, T> idxToVal, Func<T, T, T> mergeSubTrees) => new CReRooting<T>(this, idxToVal, mergeSubTrees);
        public class CReRooting<T>
        {
            LIB_Tree tree;
            Dictionary<int, T>[] dp;
            Func<T, T, T> f;
            Func<long, T> g;
            Func<long, long, T, T> g2;
            Func<T, T, T> h;
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public CReRooting(LIB_Tree tree, Func<long, T> idxToVal, Func<T, T, T> mergeSubTrees)
            {
                this.tree = tree;
                dp = Enumerable.Repeat(0, tree.N).Select(_ => new Dictionary<int, T>()).ToArray();
                f = mergeSubTrees;
                g = idxToVal;
                g2 = (r, p, v) => v;
                h = (v, t) => t;
            }
            public T this[long vtx, long parent]
            {
                [MethodImpl(MethodImplOptions.AggressiveInlining)]
                get { return dp[vtx][(int)parent]; }
            }
            /// <summary>
            /// 鬆らせ逡ｪ蜿ｷ(root, parent)縺ｧ陦ｨ縺呵ｾｺ縺ｨroot繧偵Ν繝ｼ繝医→縺吶ｋ驛ｨ蛻・惠繧偵・繝ｼ繧ｸ縺吶ｋ繝｡繧ｽ繝・ラ繧定ｨｭ螳・            /// </summary>
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public void SetMergeEdgeAndSubtree(Func<long, long, T, T> mergeEdgeAndSubtree) { g2 = mergeEdgeAndSubtree; }
            /// <summary>
            /// 鬆らせ縺ｨ驛ｨ蛻・惠縺ｮ邨先棡繧偵・繝ｼ繧ｸ(vertex, subtrees)縺吶ｋ繝｡繧ｽ繝・ラ繧定ｨｭ螳・            /// </summary>
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public void SetMergeVertexAndSubtree(Func<T, T, T> mergeVertexAndSubtree) { h = mergeVertexAndSubtree; }
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public void Build()
            {
                var done = new bool[tree.N];
                Action<long, long, T> upd = (vtx, rt, val) =>
                {
                    if (vtx == -1) return;
                    if (done[vtx]) dp[vtx][-1] = f(dp[vtx][-1], g2(rt, vtx, val));
                    else dp[vtx][-1] = g2(rt, vtx, val);
                    done[vtx] = true;
                };
                foreach (var item in tree.BFSFromLeaf(0))
                {
                    var ary = tree.path[item.node].Where(e => e != item.parent).ToArray();
                    var val = g(item.node);
                    if (ary.Length > 0)
                    {
                        var acc = g2(ary[0], item.node, dp[ary[0]][(int)item.node]);
                        foreach (var item2 in ary.Skip(1)) acc = f(acc, g2(item2, item.node, dp[item2][(int)item.node]));
                        val = h(val, acc);
                    }
                    upd(item.parent, item.node, dp[item.node][(int)item.parent] = val);
                }
                var swag = new LIB_SlidingWindowAggregation<T>(f);
                Action<int, int> process = (node, parent) =>
                {
                    var val = g(node);
                    if (tree.path[node].Count == 1)
                    {
                        var x = tree.path[node][0];
                        if (x != parent) upd(x, node, dp[node][x] = val);
                    }
                    else if (tree.path[node].Count == 2)
                    {
                        var x = tree.path[node][0]; var y = tree.path[node][1];
                        if (x != parent) upd(x, node, dp[node][x] = h(val, g2(y, node, dp[y][node])));
                        if (y != parent) upd(y, node, dp[node][y] = h(val, g2(x, node, dp[x][node])));
                    }
                    else if (tree.path[node].Count == 3)
                    {
                        var x = tree.path[node][0]; var y = tree.path[node][1]; var z = tree.path[node][2];
                        if (x != parent) upd(x, node, dp[node][x] = h(val, f(g2(y, node, dp[y][node]), g2(z, node, dp[z][node]))));
                        if (y != parent) upd(y, node, dp[node][y] = h(val, f(g2(x, node, dp[x][node]), g2(z, node, dp[z][node]))));
                        if (z != parent) upd(z, node, dp[node][z] = h(val, f(g2(x, node, dp[x][node]), g2(y, node, dp[y][node]))));
                    }
                    else if (tree.path[node].Count == 4)
                    {
                        var x = tree.path[node][0]; var y = tree.path[node][1]; var z = tree.path[node][2]; var w = tree.path[node][3];
                        var xy = f(g2(x, node, dp[x][node]), g2(y, node, dp[y][node]));
                        var zw = f(g2(z, node, dp[z][node]), g2(w, node, dp[w][node]));
                        if (x != parent) upd(x, node, dp[node][x] = h(val, f(g2(y, node, dp[y][node]), zw)));
                        if (y != parent) upd(y, node, dp[node][y] = h(val, f(g2(x, node, dp[x][node]), zw)));
                        if (z != parent) upd(z, node, dp[node][z] = h(val, f(xy, g2(w, node, dp[w][node]))));
                        if (w != parent) upd(w, node, dp[node][w] = h(val, f(xy, g2(z, node, dp[z][node]))));
                    }
                    else
                    {
                        swag.Clear();
                        var pre = new T[tree.path[node].Count];
                        for (var i = 0; i < pre.Length; ++i) swag.PushBack(pre[i] = g2(tree.path[node][i], node, dp[tree.path[node][i]][node]));
                        for (var i = 0; i < pre.Length; ++i)
                        {
                            var item2 = tree.path[node][i];
                            swag.PopFront();
                            if (item2 != parent) upd(item2, node, dp[node][item2] = h(val, swag.Aggregate()));
                            swag.PushBack(pre[i]);
                        }
                    }
                };
                foreach (var item in tree.BFSFromRoot(0)) process((int)item.node, (int)item.parent);
                for (var i = 1; i < tree.N; i++) dp[i][-1] = done[i] ? h(g(i), dp[i][-1]) : g(i);
            }
        }
    }
    class LIB_FastIO
    {
        public LIB_FastIO() { str = Console.OpenStandardInput(); }
        readonly Stream str;
        readonly byte[] buf = new byte[1024];
        int len, ptr;
        public bool isEof = false;
        public bool IsEndOfStream { get { return isEof; } }
        byte read()
        {
            if (isEof) throw new EndOfStreamException();
            if (ptr >= len)
            {
                ptr = 0;
                if ((len = str.Read(buf, 0, 1024)) <= 0)
                {
                    isEof = true;
                    return 0;
                }
            }
            return buf[ptr++];
        }
        char Char()
        {
            byte b = 0;
            do b = read();
            while (b < 33 || 126 < b);
            return (char)b;
        }
        virtual public string Scan()
        {
            var sb = new StringBuilder();
            for (var b = Char(); b >= 33 && b <= 126; b = (char)read())
                sb.Append(b);
            return sb.ToString();
        }
        virtual public long Long()
        {
            long ret = 0; byte b = 0; var ng = false;
            do b = read();
            while (b != '-' && (b < '0' || '9' < b));
            if (b == '-') { ng = true; b = read(); }
            for (; true; b = read())
            {
                if (b < '0' || '9' < b)
                    return ng ? -ret : ret;
                else ret = ret * 10 + b - '0';
            }
        }
        virtual public double Double() { return double.Parse(Scan(), CultureInfo.InvariantCulture); }
    }
    class LIB_FastIODebug : LIB_FastIO
    {
        Queue<string> param = new Queue<string>();
        string NextString() { if (param.Count == 0) foreach (var item in Console.ReadLine().Split(' ')) param.Enqueue(item); return param.Dequeue(); }
        public LIB_FastIODebug() { }
        public override string Scan() => NextString();
        public override long Long() => long.Parse(NextString());
        public override double Double() => double.Parse(NextString());
    }
    class LIB_SlidingWindowAggregation<T>
    {
        T[][] list;
        T[][] agg;
        int[] size;
        Func<T, T, T> fun;
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LIB_SlidingWindowAggregation(IEnumerable<T> ary, Func<T, T, T> f)
        {
            list = new T[2][]; agg = new T[2][]; size = new int[2];
            fun = f;
            list[0] = new T[16]; agg[0] = new T[16]; size[0] = 0;
            if (ary.Any())
            {
                var temp = ary.ToArray();
                size[1] = temp.Length;
                list[1] = new T[size[1]];
                agg[1] = new T[size[1]];
                for (var i = 0; i < list[1].Length; i++)
                {
                    list[1][i] = temp[i];
                    if (i == 0) agg[1][i] = temp[i];
                    else agg[1][i] = fun(agg[1][i - 1], temp[i]);
                }
            }
            else
            {
                list[1] = new T[16]; agg[1] = new T[16]; size[1] = 0;
            }
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LIB_SlidingWindowAggregation(Func<T, T, T> f) : this(new T[0], f) { }
        public int Count => size[0] + size[1];
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Clear()
        {
            size[0] = size[1] = 0;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        void Push(int lista, T val)
        {
            if (list[lista].Length == size[lista])
            {
                var newAry = new T[size[lista] * 2];
                var newAgg = new T[size[lista] * 2];
                Array.Copy(list[lista], newAry, size[lista]);
                Array.Copy(agg[lista], newAgg, size[lista]);
                list[lista] = newAry;
                agg[lista] = newAgg;
            }
            if (size[lista] == 0) agg[lista][0] = val;
            else if (lista == 0) agg[lista][size[lista]] = fun(val, agg[lista][size[lista] - 1]);
            else agg[lista][size[lista]] = fun(agg[lista][size[lista] - 1], val);
            list[lista][size[lista]++] = val;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void PushBack(T val) => Push(1, val);
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void PushFront(T val) => Push(0, val);
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        T Pop(int lista)
        {
            var listb = 1 - lista;
            if (size[lista] == 0)
            {
                if (size[listb] == 0) throw new Exception();
                var mid = (size[listb] - 1) / 2;
                if (list[lista].Length <= mid)
                {
                    list[lista] = new T[mid + 1];
                    agg[lista] = new T[mid + 1];
                }
                size[lista] = 0;
                for (var i = mid; i >= 0; i--)
                {
                    if (size[lista] == 0) agg[lista][size[lista]] = list[listb][i];
                    else if (lista == 0) agg[lista][size[lista]] = fun(list[listb][i], agg[lista][size[lista] - 1]);
                    else agg[lista][size[lista]] = fun(agg[lista][size[lista] - 1], list[listb][i]);
                    list[lista][size[lista]++] = list[listb][i];
                }
                for (var i = mid + 1; i < size[listb]; i++)
                {
                    var idx = i - mid - 1;
                    if (idx == 0) agg[listb][idx] = list[listb][i];
                    else if (lista == 0) agg[listb][idx] = fun(list[listb][i], agg[listb][idx - 1]);
                    else agg[listb][idx] = fun(agg[listb][idx - 1], list[listb][i]);
                    list[listb][idx] = list[listb][i];
                }
                size[listb] -= size[lista];
            }
            return list[lista][--size[lista]];
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public T PopBack() => Pop(1);
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public T PopFront() => Pop(0);
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public T Aggregate()
        {
            if (size[0] == 0 && size[1] == 0) throw new Exception();
            else if (size[1] == 0) return agg[0][size[0] - 1];
            else if (size[0] == 0) return agg[1][size[1] - 1];
            else return fun(agg[0][size[0] - 1], agg[1][size[1] - 1]);
        }
    }
}