Coin Exchange
Time limit8sMemory limit256 MB
Find the fewest swaps along graph edges that place every black coin on a black vertex and every white coin on a white vertex.
- Level
Medium7 of 10
- Topics
- Shortest path, Graph, Dynamic programming
- Solved
- No attempts yet
Problem
You are given an undirected graph with vertex set and edge set . The graph is connected, so at least one path runs between every pair of vertices. Each vertex is black or white, and every vertex holds exactly one coin. Each coin is black or white.
A coin exchange takes two vertices joined by an edge and swaps the two coins sitting on them.

Figure 1. Examples of a coin exchange (2 with 5, 5 with 6, 1 with 5). The color of a square is the color of a coin.
You want every black coin to end up on a black vertex and every white coin on a white vertex. Find the minimum number of coin exchanges that achieves this.
Input
The first line contains the number of test cases .
The first line of each test case contains the number of vertices and the number of edges (, ). Vertices are numbered 1 to . Each of the next lines contains two vertices and joined by an edge (). The next line contains integers, each 0 or 1, where the -th integer is the color of vertex . 0 is black and 1 is white. The last line contains integers, each 0 or 1, where the -th integer is the color of the coin sitting on vertex .
Only inputs where every coin can be matched to a vertex of the same color are given.
Output
For each test case, print on its own line the minimum number of coin exchanges needed to put every coin on a vertex of its own color.