Problem:
Score : 1500 points

Problem Statement

You are given a tree with N vertices numbered 1, 2, ..., N. The i-th edge connects Vertex a_i and Vertex b_i.
You are also given a string S of length N consisting of 0 and 1. The i-th character of S represents the number of pieces placed on Vertex i.

Snuke will perform the following operation some number of times:

Choose two pieces the distance between which is at least 2, and bring these pieces closer to each other by 1. More formally, choose two vertices u and v, each with one or more pieces, and consider the shortest path between them. Here the path must contain at least two edges. Then, move one piece from u to its adjacent vertex on the path, and move one piece from v to its adjacent vertex on the path.

By repeating this operation, Snuke wants to have all the pieces on the same vertex. Is this possible?
If the answer is yes, also find the minimum number of operations required to achieve it.

Constraints

2 \leq N \leq 2000

|S| = N

S consists of 0 and 1, and contains at least one 1.

1 \leq a_i, b_i \leq N(a_i \neq b_i)

The edges (a_1, b_1), (a_2, b_2), ..., (a_{N - 1}, b_{N - 1}) forms a tree.

Input

Input is given from Standard Input in the following format:

N
S
a_1 b_1
a_2 b_2
:
a_{N - 1} b_{N - 1}

Output

If it is impossible to have all the pieces on the same vertex, print -1. If it is possible, print the minimum number of operations required.

Sample Input 1

7
0010101
1 2
2 3
1 4
4 5
1 6
6 7

Sample Output 1

3

We can gather all the pieces in three operations as follows:

Choose the pieces on Vertex 3 and 5.

Choose the pieces on Vertex 2 and 7.

Choose the pieces on Vertex 4 and 6.

Sample Input 2

7
0010110
1 2
2 3
1 4
4 5
1 6
6 7

Sample Output 2

-1

Sample Input 3

2
01
1 2

Sample Output 3

0

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

use std::cmp::*;
use std::io::*;
use utils::*;

pub fn main() {
    let i = stdin();
    let mut o = Vec::new();
    run(i.lock(), &mut o);
    stdout().write_all(&o).unwrap();
}

#[derive(Clone)]
struct Node {
    edges: Vec<Edge>,      // 辺
    score_computed: usize, // edgesの中でscoreが計算済みの項目の数
}
impl Node {
    fn new() -> Self {
        Node {
            edges: Vec::new(),
            score_computed: 0,
        }
    }

    /// 全てのコマをこの頂点に集めるために必要な操作回数
    fn cost(&self) -> Option<usize> {
        let mut dist_sum = 0;
        let mut dist_max = 0;
        for e in &self.edges {
            let (count, dist) = e.score.unwrap();
            let dist = dist + count;
            dist_sum += dist;
            dist_max = max(dist_max, dist);
        }
        if dist_sum % 2 == 0 && dist_max <= dist_sum / 2 {
            Some(dist_sum / 2)
        } else {
            None
        }
    }
}
#[derive(Clone)]
struct Edge {
    to: usize,
    idx_rev: usize,                // 逆向きの辺の ns[to].edges 内でのインデックス
    score: Option<(usize, usize)>, // (to方向にあるコマの数, to方向にある全てのコマとの距離の和)
}
impl Edge {
    fn new(to: usize, idx_rev: usize) -> Self {
        Edge {
            to: to,
            idx_rev: idx_rev,
            score: None,
        }
    }
}


pub fn run<R: BufRead, W: Write>(i: R, o: &mut W) {
    let mut i = CpReader::new(i);
    let n = i.read::<usize>();

    let mut ns = vec![Node::new(); n];
    let s = i.read_line().to_vec();

    for _ in 0..n - 1 {
        let (a, b) = i.read::<(usize, usize)>();
        let (a, b) = (a - 1, b - 1);

        let edges_len_a = ns[a].edges.len();
        let edges_len_b = ns[b].edges.len();

        ns[a].edges.push(Edge::new(b, edges_len_b));
        ns[b].edges.push(Edge::new(a, edges_len_a));
    }
    let ans = solve(&s, ns).map(|x| x as isize).unwrap_or(-1);
    writeln!(o, "{}", ans).unwrap();
}

fn solve(s: &[u8], mut ns: Vec<Node>) -> Option<usize> {
    let mut q = Vec::new();
    for i in 0..ns.len() {
        if ns[i].edges.len() == 1 {
            q.push(i);
        }
    }
    while let Some(i0) = q.pop() {
        let mut all_count = 0;
        let mut all_dist = 0;
        let mut j_begin = 0;
        let mut j_end = ns[i0].edges.len();
        for i1 in 0..ns[i0].edges.len() {
            let e = &ns[i0].edges[i1];
            if let Some((count, dist)) = e.score {
                all_count += count;
                all_dist += dist;
            } else {
                j_begin = i1;
                j_end = i1 + 1;
            }
        }
        all_dist += all_count;
        if s[i0] == b'1' {
            all_count += 1;
        }
        for j in j_begin..j_end {
            let mut all_count = all_count;
            let mut all_dist = all_dist;
            let k;
            {
                let e = &ns[i0].edges[j];
                k = (e.to, e.idx_rev);
                if let Some((count, dist)) = e.score {
                    all_count -= count;
                    all_dist -= dist + count;
                }
            }
            let node = &mut ns[k.0];
            if node.edges[k.1].score.is_none() {
                node.edges[k.1].score = Some((all_count, all_dist));
                node.score_computed += 1;
                if node.score_computed + 1 >= node.edges.len() {
                    q.push(k.0);
                }
            }
        }
    }
    ns.iter().filter_map(Node::cost).min()
}

pub mod utils {
    use super::*;

    pub struct CpReader<R: BufRead> {
        r: R,
        b: Vec<u8>,
    }
    impl<R: BufRead> CpReader<R> {
        pub fn new(r: R) -> Self {
            CpReader {
                r: r,
                b: Vec::new(),
            }
        }
        pub fn read_word(&mut self) -> &[u8] {
            self.b.clear();
            let mut consume = 0;
            loop {
                self.r.consume(consume);
                let b = self.r.fill_buf().unwrap();
                assert!(b.len() != 0);
                if let Some(p) = b.iter().position(|&x| x == b' ' || x == b'\n') {
                    self.b.extend_from_slice(&b[..p]);
                    consume = p + 1;
                    break;
                }
                self.b.extend_from_slice(b);
                consume = b.len();
            }
            self.r.consume(consume);
            &self.b
        }
        pub fn read_word_str(&mut self) -> &str {
            unsafe { std::str::from_utf8_unchecked(self.read_word()) }
        }

        pub fn read_line(&mut self) -> &[u8] {
            self.b.clear();
            self.r.read_until(b'\n', &mut self.b).unwrap();
            if self.b.last() == Some(&b'\n') {
                &self.b[..self.b.len() - 1]
            } else {
                &self.b
            }
        }
        pub fn read_line_str(&mut self) -> &str {
            unsafe { std::str::from_utf8_unchecked(self.read_line()) }
        }

        pub fn read<T: CpIn>(&mut self) -> T {
            T::read_from(self)
        }

        pub fn read_vec<T: CpIn>(&mut self, n: usize) -> Vec<T> {
            (0..n).map(|_| self.read()).collect()
        }
        pub fn read_iter<'a, T: CpIn>(&'a mut self, n: usize) -> CpIter<'a, R, T> {
            CpIter {
                r: self,
                n: n,
                _pd: Default::default(),
            }
        }
    }
    pub struct CpIter<'a, R: BufRead + 'a, T> {
        r: &'a mut CpReader<R>,
        n: usize,
        _pd: std::marker::PhantomData<fn() -> T>,
    }
    impl<'a, R: BufRead, T: CpIn> Iterator for CpIter<'a, R, T> {
        type Item = T;
        fn next(&mut self) -> Option<T> {
            if self.n == 0 {
                None
            } else {
                self.n -= 1;
                Some(self.r.read())
            }
        }
    }

    pub trait CpIn {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self;
    }

    impl CpIn for u64 {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
            read_u64_fast(&mut r.r)
        }
    }
    impl CpIn for i64 {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
            read_i64_fast(&mut r.r)
        }
    }
    impl CpIn for char {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
            let b = r.r.fill_buf().unwrap()[0] as char;
            r.r.consume(1);
            let s = r.r.fill_buf().unwrap()[0];
            assert!(s == b' ' || s == b'\n');
            r.r.consume(1);
            b
        }
    }

    macro_rules! cpin_tuple {
        ($($t:ident),*) => {
            impl<$($t: CpIn),*> CpIn for ($($t),*) {
                fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
                    ($($t::read_from(r)),*)
                }
            }
        };
    }

    macro_rules! cpin_cast {
        ($t_self:ty, $t_read:ty) => {
            impl CpIn for $t_self {
                fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
                    <$t_read>::read_from(r) as $t_self
                }
            }
        };
    }
    macro_rules! cpin_parse {
        ($t:ty) => {
            impl CpIn for $t {
                fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
                    r.read_word_str().parse().unwrap()
                }
            }
        };
    }
    cpin_cast!(usize, u64);
    cpin_cast!(u32, u64);
    cpin_cast!(u16, u64);
    cpin_cast!(i32, i64);
    cpin_cast!(i16, i64);
    cpin_cast!(i8, i64);

    cpin_parse!(f64);

    cpin_tuple!(T1, T2);
    cpin_tuple!(T1, T2, T3);
    cpin_tuple!(T1, T2, T3, T4);
    cpin_tuple!(T1, T2, T3, T4, T5);


    fn read_u64_fast<R: BufRead>(r: &mut R) -> u64 {
        let mut value = 0;
        loop {
            let mut idx = 0;
            let buf_len;
            {
                let buf = r.fill_buf().unwrap();
                buf_len = buf.len();
                assert!(buf_len != 0);
                while idx < buf_len && b'0' <= buf[idx] && buf[idx] <= b'9' {
                    value = value * 10 + (buf[idx] - b'0') as u64;
                    idx += 1;
                }
            }
            if idx < buf_len {
                r.consume(idx + 1);
                return value;
            }
            r.consume(idx);
        }
    }
    fn read_i64_fast<R: BufRead>(r: &mut R) -> i64 {
        let (consume, sign) = match r.fill_buf().unwrap()[0] {
            b'+' => (true, 1),
            b'-' => (true, -1),
            _ => (false, 1),
        };
        if consume {
            r.consume(1);
        }
        read_u64_fast(r) as i64 * sign
    }
}