Apple Banana Tree
Time limit1sMemory limit1024 MB
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 vertices. There are branches, each connecting two vertices, so the whole thing forms one connected graph. Vertices are numbered from 1 to , 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 . ()
The second line contains a string of length made only of A and B. The -th character represents the fruit on vertex . A is an apple, and B is a banana.
Each of the following lines contains two vertex numbers and , the endpoints of a branch. (, )
Output
If each kind of fruit can be gathered into one block, print the minimum number of moves needed. Otherwise, print -1.