Under construction

Still being built. Things may change

Apple Banana Tree

Time limit1sMemory limit1024 MB

Summary
Given a tree whose vertices are labeled A or B, find the fewest edge swaps that make each label form one connected subgraph, or -1.
Level

Medium7 of 10

Topics
Tree, Dynamic programming, DFS
Solved
No attempts yet

Problem

Karuna runs an orchard. Recently Karuna planted a strange tree called the "Apple Banana Tree" in the orchard.

The Apple Banana Tree is a tree with NN vertices. There are N−1N-1 branches, each connecting two vertices, so the whole thing forms one connected graph. Vertices are numbered from 1 to NN, and each vertex has either one apple or one banana.

Apples and bananas need different kinds of care, so Karuna wants to gather each kind of fruit into one block. Specifically, when only the vertices with apples are kept, they must form one connected graph. The same must hold for the vertices with bananas. (A case where no vertices remain also counts as one connected graph.)

Karuna can swap the fruits on two vertices joined directly by a branch. This is called a "move." A move takes a lot of stamina, so Karuna wants to reach the goal with as few moves as possible.

Determine whether each kind of fruit can be gathered into one block. If it can, find the minimum number of moves needed.

Input

The first line contains the number of vertices NN. (1≤N≤200 0001\le N\le 200\,000)

The second line contains a string of length NN made only of A and B. The ii-th character represents the fruit on vertex ii. A is an apple, and B is a banana.

Each of the following N−1N-1 lines contains two vertex numbers uu and vv, the endpoints of a branch. (1≤u,v≤N1\le u,v\le N, u≠vu\neq v)

Output

If each kind of fruit can be gathered into one block, print the minimum number of moves needed. Otherwise, print -1.

Examples2

  1. Example 1

    Input
    7
    BABBBAA
    1 2
    2 4
    4 5
    2 3
    4 6
    6 7
    
    Expected output
    7
    
  2. Example 2

    Input
    6
    BABBAB
    1 2
    2 3
    4 5
    5 6
    2 5
    
    Expected output
    -1