UVa 410 - Station Balance

Summary
Mathematically, given a list of 2n integers, we need to match them in pairs such that the imbalance factor defined in the problem is minimum.

Explanation
Since each chamber can only hold at most 2 specimens, greedy algorithm works here. Let n be the number of chambers. To simplify, we always assume that there are 2n specimens. If there are not so many, we can zero-padding it by adding some specimens of mass 0. Let the sorted list of specimen masses be {$$A_1, A_2, ..., A_{2n}$$}, we match $$A_1$$ with $$A_{2n}$$, $$A_2$$ with $$A_{2n-1}$$, ..., $$A_i$$ with $$A_{2n-i}$$, ..., and put them into separate chambers. This way, the imbalance is guaranteed to be the smallest.

Why does Greedy algorithm works for this problem? Followed is a sketch of a proof. We exploit the fact that each chamber can only hold at most 2 specimens.

Let n the number of chambers and the zero-padded sorted list of specimen masses be {$$A_1, A_2, ..., A_{2n}$$}. We have $$A_1 < A_2 < ... < A_{2n}$$. In the k'th step, we try to match $$A_k$$. Let us just look into the first step, all the rest steps are similar. By the Greedy algorithm described above, the best match of $$A_1$$ is $$A_{2n}$$. Let us denote it by { $$(A_1,A_{2n})$$ }. We want to show that the match { $$(A_1,A_{2n})$$ } is at least as good as any other match { $$(A_1,A_j)$$ }, $$1<j<2n$$.

Suppose in the match { $$(A_1,A_j)$$ }, $$A_{2n}$$ is matched to $$A_i$$, $$1<i<2n$$ and $$i \not= j$$. Let us denote it by { $$(A_1,A_j)$$, $$(A_i,A_{2n})$$ }. We claim that the match { $$(A_1,A_{2n})$$, $$(A_i,A_j)$$ } is at least as good as the previous one. Since we get the new match by simply switching $$A_j$$ and $$A_{2n}$$, the imbalance contributions from the other chambers are not changed. So, let M be the average chamber mass, we are actually comparing

$$| A_1 + A_j - M | + | A_i + A_{2n} - M |$$ and $$| A_1 + A_{2n} - M | + | A_i + A_j - M |$$.

Notice that
 * $$A_1 \leq A_i, A_j \leq A_{2n}$$ and
 * $$A_1 + A_j \leq A_1 + A_{2n}$$, $$A_i + A_j \leq A_i + A_{2n} $$ and
 * $$2 * A_1 \leq M \leq 2 * A_{2n}$$.

By studying the cases of different ranges of A. It is not hard to prove (details ignored)

$$| A_1 + A_j - M | + | A_i + A_{2n} - M | \geq | A_1 + A_{2n} - M | + | A_i + A_j - M |$$.

So, we know that { $$(A_1,A_{2n})$$ } is optimal, similarly { $$(A_1,A_{2n})$$, $$(A_2,A_{2n-1})$$ }, ....

Gotchas

 * As long as the matching is correct, it does not matter which chamber you put a pair into.
 * Do not forget the space before the chamber ID.

Input
2 3 6 3 8 3 5 51 19 27 14 33 5 9 1 2 3 5 7 11 13 17 19

Output
Set #1 0: 6 3 1: 8 IMBALANCE = 1.00000

Set #2 0: 51 1: 19 27 2: 14 33 IMBALANCE = 6.00000

Set #3 0: 1 17 1: 2 13 2: 3 11 3: 5 7 4: 19 IMBALANCE = 11.60000