UVa 10982 - Troublemakers

10982 - Troublemakers

 * http://acm.uva.es/p/v109/10982.html

Summary
This is a graph theory problem with a greedy solution.

We are given a graph with n nodes in the range 1 to n and m edges, and we want partition the graph into two partitions such that the number of edges which are contained by two nodes in the same partition is at most m/2.

Explanation
We call edges adjacent to two nodes in a single partition conflict edges.

A skeleton solution to the problem is as follows.

Assign all nodes to a single partition. While there are more than m/2 conflicts find a node x with having more than have of its edges in conflict. swap x to other partition.

Claim: The algorithm terminates with a correct partitioning.

Proof: Consider the number conflicts before and after each iteration of the loop. Since we pick x to have more conflicts than non-conflict edges, and swapping the partition of x changes every non-conflict edge to a conflict edge and vice versa, the total number of conflicts will decrease at every iteration.

We are always able to find such a heavily conflicted node x, since there are more than m/2 edges in conflict. For the sake of contradiction, assume there does not exist a node with more than half of its edges in conflict, yet there are still more than m/2 conflict edges. Let C(i) denote the number of conflict edges adjacent to node i, and let D(i) denote the total number of edges adjacent to i. Then if we count the number of conflict edges out of each node, we will double count the total number of conflict edges S, as each conflict edge is counted twice, once for its adjacent node. So $$\sum_{i = 1}^n C(i) = 2S $$, dividing each side by two yields $$\sum_{i = 1}^n C(i) / 2 = S$$. Since $$C(i) \leq D(i)/2$$ for all i by assumption, $$\sum_{i = 1}^n D(i) / 4 \leq S$$. The classical graph theory relation shows us that $$\sum_{i = 1}^n D(i) = 2m$$, so dividing by 4 we have $$\sum_{i = 1}^n D(i)/4 = m/2$$. Hence $$\sum_{i = 1}^n D(i) / 4 = m/2 \leq S$$, contradicting our assumption that there are more than m/2 conflict edges.

Gotchas

 * The same edge may be listed multiple times.

Optimizations
I tried a random assignment to the initial partitions, but surprisingly, that did not speed up (nor slow down) my implementation.

Input
10 4 3 1 2 2 3 3 4

4 6 1 2 1 3 1 4 2 3 2 4 3 4

3 0

3 1 1 2

3 1 1 3

3 2 1 2 1 3

3 1 2 3

3 2 1 2 2 3

3 2 1 3 2 3

3 3 1 2 1 3 2 3

Output
Note the output is not neccesarily unique. Case #1: 2 2 4 Case #2: 2 3 4 Case #3: 3 1 2 3 Case #4: 2 2 3 Case #5: 2 2 3 Case #6: 2 2 3 Case #7: 2 1 3 Case #8: 1 2 Case #9: 1 3 Case #10: 2 2 3