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 Rust (1.42.0) (judge verdict: Wrong Answer)

use segment_tree::SegmentTree;

pub mod segment_tree {
    #[derive(Default)]
    pub struct SegmentTree<T, F> {
        pub seg: Vec<T>,
        n: usize,
        f: F,
        init_value: T,
    }
    impl<T: Copy, F: Fn(T, T) -> T> SegmentTree<T, F> {
        pub fn new(n: usize, init_value: T, f: F) -> SegmentTree<T, F> {
            let mut m = 1;
            while m <= n {
                m <<= 1;
            }
            SegmentTree {
                seg: vec![init_value; 2 * m],
                n: m,
                f: f,
                init_value: init_value,
            }
        }
        pub fn update(&mut self, k: usize, value: T) {
            let mut k = k;
            k += self.n - 1;
            self.seg[k] = value;
            while k > 0 {
                k = (k - 1) >> 1;
                self.seg[k] = (self.f)(self.seg[2 * k + 1], self.seg[2 * k + 2]);
            }
        }
        //Get a query result in the range [left, right)
        pub fn query(&self, left: usize, right: usize) -> T {
            assert!(left < right);
            self.query_range(left, right, 0, 0, self.n)
        }
        fn query_range(
            &self,
            left: usize,
            right: usize,
            k: usize,
            left_bound: usize,
            right_bound: usize,
        ) -> T {
            if right_bound <= left || right <= left_bound {
                self.init_value
            } else if left <= left_bound && right_bound <= right {
                self.seg[k]
            } else {
                let x = self.query_range(
                    left,
                    right,
                    2 * k + 1,
                    left_bound,
                    (left_bound + right_bound) >> 1,
                );
                let y = self.query_range(
                    left,
                    right,
                    2 * k + 2,
                    (left_bound + right_bound) >> 1,
                    right_bound,
                );
                (self.f)(x, y)
            }
        }
    }
}

#[cfg(test)]
mod test {
    use super::segment_tree::SegmentTree;
    use rand::{thread_rng, Rng};

    #[test]
    fn random_update() {
        let n = 1000;
        //max segment tree
        let mut seg = SegmentTree::new(n, 0, |a, b| std::cmp::max(a, b));
        let mut v = vec![0; n];
        for _ in 0..10000 {
            let value = thread_rng().gen_range(0, 1000);
            let k = thread_rng().gen_range(0, n);
            v[k] = value;
            seg.update(k, value);
            //[0, n)
            assert_eq!(seg.query(0, n), *v.iter().max().unwrap());

            let l = thread_rng().gen_range(0, n);
            let r = thread_rng().gen_range(l, n);
            //two point
            //[l, r + 1)
            let x = v.iter().skip(l).take(r - l + 1).max().unwrap();
            assert_eq!(seg.query(l, r + 1), *x);
        }
    }
}

const MAX_N: usize = 200_010;
const INF: i32 = 1 << 30;

use std::collections::HashMap;

//type MaxSegTree = SegmentTree<usize, |a, b| std::cmp::max(a, b)>;
#[derive(Default)]
//NOTE
//declare variables to reduce the number of parameters for dp and dfs etc.
struct Solver {
    a: Vec<usize>,
    edges: Vec<Vec<usize>>,
    values: HashMap<usize, usize>,
    results: Vec<usize>,
    //cnts: HashMap<usize, usize>,
}

impl Solver {
    fn dfs<F: Fn(usize, usize) -> usize>(
        &mut self,
        pos: usize,
        pre: Option<usize>,
        seg: &mut SegmentTree<usize, F>,
    ) {
        for idx in 0..self.edges[pos].len() {
            let nxt = self.edges[pos][idx];
            //eprintln!("{} {}", pos, nxt);
            if Some(nxt) == pre {
                continue;
            }

            let v = self.values.get(&self.a[nxt]).unwrap().clone();
            //eprintln!("v: {}", v);
            let pre_v = seg.query(v, v + 1);
            let x = seg.query(0, v + 1);
            self.results[nxt] = x + 1;

            seg.update(v, x + 1);
            self.dfs(nxt, Some(pos), seg);
            seg.update(v, pre_v);
        }
    }
    fn solve(&mut self) {
        let stdin = std::io::stdin();
        let mut scn = Scanner {
            stdin: stdin.lock(),
        };
        let n: usize = scn.read();
        let a: Vec<usize> = scn.vec(n);
        let mut b = a.clone();
        b.sort();
        let mut values = HashMap::new();
        for x in b.iter() {
            let y = values.len() + 1;
            values.entry(*x).or_insert(y);
        }
        //eprintln!("{:?}", values);
        let mut edges = vec![vec![]; MAX_N];
        let uv: Vec<_> = (0..n - 1)
            .map(|_| {
                let u: usize = scn.read();
                let v: usize = scn.read();
                edges[u - 1].push(v - 1);
                edges[v - 1].push(u - 1);
                (u - 1, v - 1)
            })
            .collect();

        self.a = a;
        self.edges = edges;
        self.results = vec![0; n];
        self.values = values.clone();
        let mut seg = SegmentTree::new(MAX_N, 0, |a: usize, b: usize| std::cmp::max(a, b));
        seg.update(*values.get(&self.a[0]).unwrap(), 1);
        self.results[0] = 1;
        self.dfs(0, None, &mut seg);

        for x in self.results.iter() {
            println!("{}", x);
        }
    }
}

fn main() {
    std::thread::Builder::new()
        .stack_size(64 * 1024 * 1024) // 64MB
        .spawn(|| {
            let mut solver = Solver::default();
            solver.solve()
        })
        .unwrap()
        .join()
        .unwrap();
}
pub mod utils {
    const DYX: [(isize, isize); 8] = [
        (0, 1),   //right
        (1, 0),   //down
        (0, -1),  //left
        (-1, 0),  //top
        (1, 1),   //down right
        (-1, 1),  //top right
        (1, -1),  //down left
        (-1, -1), //top left
    ];

    pub fn try_adj(y: usize, x: usize, dir: usize, h: usize, w: usize) -> Option<(usize, usize)> {
        let ny = y as isize + DYX[dir].0;
        let nx = x as isize + DYX[dir].1;
        if ny >= 0 && nx >= 0 {
            let ny = ny as usize;
            let nx = nx as usize;
            if ny < h && nx < w {
                Some((ny, nx))
            } else {
                None
            }
        } else {
            None
        }
    }
}

//snippet from kenkoooo
pub struct Scanner<R> {
    stdin: R,
}

impl<R: std::io::Read> Scanner<R> {
    pub fn read<T: std::str::FromStr>(&mut self) -> T {
        use std::io::Read;
        let buf = self
            .stdin
            .by_ref()
            .bytes()
            .map(|b| b.unwrap())
            .skip_while(|&b| b == b' ' || b == b'\n' || b == b'\r')
            .take_while(|&b| b != b' ' && b != b'\n' && b != b'\r')
            .collect::<Vec<_>>();
        unsafe { std::str::from_utf8_unchecked(&buf) }
            .parse()
            .ok()
            .expect("Parse error.")
    }
    pub fn read_line(&mut self) -> String {
        use std::io::Read;
        let buf = self
            .stdin
            .by_ref()
            .bytes()
            .map(|b| b.unwrap())
            .skip_while(|&b| b == b'\n' || b == b'\r')
            .take_while(|&b| b != b'\n' && b != b'\r')
            .collect::<Vec<_>>();
        unsafe { std::str::from_utf8_unchecked(&buf) }
            .parse()
            .ok()
            .expect("Parse error.")
    }
    pub fn vec<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.read()).collect()
    }

    pub fn chars(&mut self) -> Vec<char> {
        self.read::<String>().chars().collect()
    }
}