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: Accepted)

// https://atcoder.jp/contests/agc034/tasks/agc034_e
//
#![allow(unused_imports)]
use std::cmp::*;
use std::collections::*;
use std::fmt::*;
use std::io::*;
use std::str::*;

macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};

    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };

    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };

    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };

    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        println!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

const INF: u64 = 1e12 as u64;

type Graph = Vec<Vec<usize>>;

struct Solver {
    tree: Graph,
    s: Vec<u64>,
    weight: Vec<u64>,
    count: Vec<u64>,
}

impl Solver {
    fn dfs(&mut self, now: usize, par: usize) -> (u64, u64) {
        let mut weight = 0;
        let mut count = self.s[now];
        for to in self.tree[now].clone() {
            if to == par {
                continue;
            }
            let (w, c) = self.dfs(to, now);
            weight += w + c;
            count += c;
        }
        self.weight[now] = weight;
        self.count[now] = count;
        (weight, count)
    }

    fn find_most(&mut self, root: usize) -> (usize, u64) {
        let mut most = 0;
        let mut rt = 0;
        let all = self.weight[root];
        for to in self.tree[root].clone() {
            if all < self.weight[to] {
                continue;
            }
            let cw = self.weight[to] + self.count[to];
            if most < cw {
                most = cw;
                rt = to;
            }
        }
        (rt, most)
    }

    fn dfs2(&mut self, now: usize, par: usize) -> u64 {
        let mut most = 0;
        let mut count = 0;
        for to in self.tree[now].clone() {
            if par == to {
                continue;
            }
            count += self.dfs2(to, now);

            let cw = self.weight[to] + self.count[to];
            if most < cw {
                most = cw;
            }
        }
        self.weight[now] -= count * 2;
        if most * 2 <= self.weight[now] {
            count += self.weight[now] / 2;
            self.weight[now] %= 1;
        } else {
            let left = self.weight[now] - most;
            count += left;
            self.weight[now] -= left * 2;
        }
        count
    }

    fn solve(&mut self, root: usize) -> u64 {
        let n = self.tree.len();
        self.dfs(root, n);

        let all = self.weight[root];
        if all % 2 == 1 {
            return INF;
        }

        let (rt, most) = self.find_most(root);
        if most * 2 <= all {
            return all / 2;
        }
        let raise = (2 * most - all) / 2;
        let max_count = self.dfs2(rt, root);
        if max_count >= raise {
            return all / 2;
        }
        return INF;
    }
}


fn main() {
    input! {
        n: usize,
        s: chars,
        edges: [(usize1, usize1); n-1],
    };
    let mut tree = vec![vec![]; n];
    for &e in &edges {
        tree[e.0].push(e.1);
        tree[e.1].push(e.0);
    }
    let si = s.iter().map(|&c| (c as u64) - ('0' as u64)).collect();
    let mut cost = INF;
    let mut slv = Solver { tree: tree, s: si, weight: vec![0; n], count: vec![0; n] };
    for i in 0..n {
        cost = min(cost, slv.solve(i));
    }
    if cost == INF {
        println!("-1");
    } else {
        println!("{}", cost);
    }
}