Diplomacy
Time limit1sMemory limit256 MB
Each month one same-party friend group switches parties with the two sides alternating, and the goal is the fewest months to unite all governors in one party.
- Level
Medium7 of 10
- Topics
- Graph, Shortest path, BFS
- Solved
- No attempts yet
Problem
You are a senator in an ancient empire ruled by a dictator. You have joined a secret committee of senators from both parties that is plotting to overthrow him. The plot succeeds only if every state in the empire backs it, and that requires every state governor to belong to the same party.
Right now each governor belongs to either the Orange Party or the Purple Party. You are confident that you can get either party behind the plot, so it does not matter which party wins out in the end.
The committee has studied the political situation. Two governors influence each other when they are friends and belong to the same party. Each month one lobbyist does whatever it takes to make a single governor switch parties. When that happens, every friend of that governor who belonged to the same party switches as well, and so do the friends of those friends who belonged to that party, and the change keeps spreading. To avoid suspicion the committee alternates Orange and Purple lobbyists from month to month. In the first month it may start with either party.
The committee also knows which governors are friends. The friendship graph is connected, so there is no isolated group whose members are friends only with each other.
Find the minimum number of months needed for every governor to belong to the same party.
Input
The input contains several test cases. The first line of each test case has two integers and (, ), where is the number of governors and is the number of known friendships. The second line has integers, each 0 or 1, giving the current party of governors 1 through in order. 0 is Orange and 1 is Purple. Each of the next lines has two integers and (), meaning that governor and governor are friends. Friendship goes both ways: if is a friend of , then is a friend of . All pairs are distinct. In every test case the friendship graph is connected. The input ends with a line holding two zeros, and that line is not a test case.
Output
For each test case, print one integer, the minimum number of months needed for every governor to belong to the same party. Print one integer per line, and do not print blank lines between them.