No.2205 Lights Out on Christmas Tree
タグ : / 解いたユーザー数 96
作問者 :
srjywrdnprkt
/ テスター :
👑 Problem Statement
You are given a tree with $N$ vertices numbered from $1$ to $N$. The $i$-th edge connects vertex $a_i$ and vertex $b_i$.
Each vertex is painted either white or black, and the color of vertex $i$ is $c_i$, where $c_i=0$ represents white and $c_i=1$ represents black.
You may perform the following operation any number of times, possibly 0. Determine whether it is possible to make all vertices black, and if it is possible, find the minimum number of operations required.
(Operation)
Choose one $i$ satisfying $1\leq i \leq N-1$, and invert the colors of vertex $a_i$ and vertex $b_i$. That is, a black vertex becomes white, and a white vertex becomes black.
Input
$N$
$a_1~b_1$
$\vdots$
$a_{N-1}~b_{N-1}$
$c_1~\cdots~c_N$
All inputs are integers and satisfy the following constraints.
- $2\leq N \leq 2\times 10^5$
- $1\leq a_i < b_i \leq N$
- If $i\neq j$, then $(a_i, b_i)\neq(a_j, b_j)$
- $c_i$ is 0 or 1
Output
Output the minimum number of operations required to make all vertices black.
However, if it is impossible to make all vertices black no matter how many operations are performed, output -1.
Print a newline at the end.
Sample
Sample 1
Input
3 1 2 2 3 0 1 0
Output
2
First, perform the operation on edge 1, then perform the operation on edge 2. The colors of the vertices then change as $(0, 1, 0)\to(1, 0, 0)\to(1, 1, 1)$.
It is impossible to make all vertices black with 1 or fewer operations, so the answer is 2.
Sample 2
Input
3 1 2 2 3 1 0 1
Output
-1
No matter how many operations are performed, it is impossible to make all vertices black.
Sample 3
Input
10 1 4 3 5 5 9 8 10 5 7 1 3 4 10 2 9 6 9 1 0 0 0 1 0 0 0 1 1
Output
6
提出するには、Twitter 、GitHub、 Googleもしくは右上の雲マークをクリックしてアカウントを作成してください。