Problem:
Score : 700 points

Problem Statement

There is a tree with N vertices, numbered 1 through N.
The i-th of the N-1 edges connects vertices a_i and b_i.

Currently, there are A_i stones placed on vertex i.
Determine whether it is possible to remove all the stones from the vertices by repeatedly performing the following operation:

Select a pair of different leaves. Then, remove exactly one stone from every vertex on the path between those two vertices.
Here, a leaf is a vertex of the tree whose degree is 1, and the selected leaves themselves are also considered as vertices on the path connecting them.

Note that the operation cannot be performed if there is a vertex with no stone on the path.

Constraints

2 ≦ N ≦ 10^5

1 ≦ a_i,b_i ≦ N

0 ≦ A_i ≦ 10^9

The given graph is a tree.

Input

The input is given from Standard Input in the following format:

N
A_1 A_2 … A_N
a_1 b_1
:
a_{N-1} b_{N-1}

Output

If it is possible to remove all the stones from the vertices, print YES. Otherwise, print NO.

Sample Input 1

5
1 2 1 1 2
2 4
5 2
3 2
1 3

Sample Output 1

YES

All the stones can be removed, as follows:

Select vertices 4 and 5. Then, there is one stone remaining on each vertex except 4.

Select vertices 1 and 5. Then, there is no stone on any vertex.

Sample Input 2

3
1 2 1
1 2
2 3

Sample Output 2

NO

Sample Input 3

6
3 2 2 2 2 2
1 2
2 3
1 4
1 5
4 6

Sample Output 3

YES

Solution in Rust (1.15.1) (judge verdict: Wrong Answer)

// use std::ops::{Index, IndexMut};
// use std::cmp::{Ordering, min, max};
// use std::collections::{BinaryHeap, BTreeMap};
// use std::collections::btree_map::Entry::{Occupied, Vacant};
// use std::clone::Clone;

fn getline() -> String{
    let mut res = String::new();
    std::io::stdin().read_line(&mut res).ok();
    res
}

macro_rules! readl {
    ($t: ty) => {
        {
            let s = getline();
            s.trim().parse::<$t>().unwrap()
        }
    };
    ($( $t: ty),+ ) => {
        {
            let s = getline();
            let mut iter = s.trim().split(' ');
            ($(iter.next().unwrap().parse::<$t>().unwrap(),)*) 
        }
    };
}

macro_rules! readlvec {
    ($t: ty) => {
        {
            let s = getline();
            let iter = s.trim().split(' ');
            iter.map(|x| x.parse().unwrap()).collect::<Vec<$t>>()
        }
    }
}

macro_rules! mvec {
    ($v: expr, $s: expr) => {
        vec![$v; $s]
    };
    ($v: expr, $s: expr, $($t: expr),*) => {
        vec![mvec!($v, $($t),*); $s]
    };
}

macro_rules! debug {
    ($x: expr) => {
        println!("{}: {:?}", stringify!($x), $x)
    }
}

type Cost = i64;

#[derive(Clone)]
struct Edge {
    to: usize,
    cost: Cost,
}

impl Ord for Edge {
    fn cmp(&self, other: &Edge) -> std::cmp::Ordering {
        (-self.cost).cmp(&(-other.cost))
    }
}

impl PartialOrd for Edge {
    fn partial_cmp(&self, other: &Edge) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Eq for Edge {}

impl PartialEq for Edge {
    fn eq(&self, other: &Edge) -> bool {
        self.cost == other.cost
    }
}

#[derive(Clone)]
struct Graph {
    adj: Vec<Vec<Edge>>,
}

impl std::ops::Index<usize> for Graph {
    type Output = Vec<Edge>;

    fn index(&self, i: usize) -> &Vec<Edge> {
        &self.adj[i]
    }
}

impl std::ops::IndexMut<usize> for Graph {
    fn index_mut<'a>(&'a mut self, i: usize) -> &'a mut Vec<Edge> {
        &mut self.adj[i]
    }
}

impl Graph {

    fn new(n: usize) -> Graph{
        Graph {
            adj: vec![vec![]; n],
        }
    }

    fn size(&self) -> usize{
        self.adj.capacity()
    }

    fn add_edge(&mut self, from: usize, to_: usize, cost_: Cost) {
        self.adj[from].push(Edge{to: to_, cost: cost_});
    }

    fn add_uedge(&mut self, from: usize, to_: usize, cost_: Cost) {
        self.add_edge(from, to_, cost_);
        self.add_edge(to_, from, cost_);
    }
}


fn printiter<'a, T>(v: &'a T)
where
    &'a T: std::iter::IntoIterator, 
    <&'a T as std::iter::IntoIterator>::Item: std::fmt::Display {
    for (i,e) in v.into_iter().enumerate() {
        if i != 0 {
            print!(" ");
        }
        print!("{}", e);
    }
    println!("");
}

impl Graph {
    fn solve(&self, p: usize, pre: usize, a: &Vec<i64>) -> Option<i64> {
        // debug!(p);
        let g = self;
        let mut sum = 0;
        let mut max = 0;
        let mut cnt = 0;
        for e in &g[p] {
            if e.to != pre {
                cnt += 1;
                let ret = g.solve(e.to, p, a);
                if let Some(val) = ret {
                    max = std::cmp::max(max, val);
                    sum += val;
                } else {
                    return None;
                }
            }
        }
        
        // debug!(p);
        // debug!(a[p]);
        // debug!(sum);
        // debug!(max);
        if cnt == 0 {
            Some(a[p])
        } else if cnt == 1 {
            if sum == a[p] {
                Some(a[p])
            } else {
                None
            }
        } else if a[p] <= sum && sum <= 2*a[p] && 2*(sum-a[p]) >= 2*(max-(sum-a[p])) {
            // debug!(sum-a[p]);
            Some(2*a[p]-sum)
        } else {
            // debug!(-1);
            None
        }
    }
}

fn main() {
    let n = readl!(usize);
    let a = readlvec!(i64);
    let mut g = Graph::new(n);
    for _ in 0..n-1 {
        let (a, b) = readl!(usize, usize);
        g.add_uedge(a-1, b-1, -1);
    }
    let g = g;
    if None == g.solve(0, n+1, &a) {
        println!("NO");
    } else {
        println!("YES");
    }
}