Evolve the problem to 2-dimension array.
There is a matrix, m x n. Several groups of people locate at some certain spots. In the following example, there are three groups and the number 4 indicates there are four people in this group. Now we want to find a meeting point in the matrix so that the cost of all groups moving to that point is the minimum.
The solution is that find the weighted median from x and y direction.
For example, the matrix is as follow:
Then, the sequence in x direction is 4 3 1 6 5, the sequence in y direction is 7 4 5 3. We find the weighted median both in x and y direction.
For the sequence 7 4 5 3, we think like this, there are 4 cities in a line, which continuously locate at 1, 2, 3, 4. The weight of them are 7, 4, 5, 3.
So the sequence is 1 1 1 1 1 1 1 2 2 2 2 3 3 3 3 3 4 4 4. So the median is 10th , which is 2, which symbolizes 4. By the same way, we can find the 10th element in 4 3 1 6 5 exists in 6. So the weighted median is array[3][1].