Stick Lengths In this problem , sort the array and I have to make all sticks size equal to array[n/2] ( n/2 = median ) then answer should be the minimum. But why I choose median index. Can anyone explain, Please ? Thanks in advance.
# | User | Rating |
---|---|---|
1 | tourist | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | awoo | 154 |
8 | Dominater069 | 154 |
10 | luogu_official | 150 |
Stick Lengths In this problem , sort the array and I have to make all sticks size equal to array[n/2] ( n/2 = median ) then answer should be the minimum. But why I choose median index. Can anyone explain, Please ? Thanks in advance.
Name |
---|
These kind of problems get solved by finding the medium element. Assume the stick lengths to be points on the X0 axis. We need to move all points into a single one while having the shortest possible distance sum of moving.
That single point is at a location where left of it are the same number of points as right of it. Because if we got more points on one of the sides we could move the point into that direction by one unit, which would decrease the sum of distances on that side by the number of elements. And increases the sum on the other side by the number of elements on the other side.
So, to find the point with minimum sum we need to move it in direction of the half with more points until both halfes are same.
You can think about it following way : If you move to the left or to the right from n/2, try to see the change in cost.
Let's assume consider a simple case , we have odd number of terms and the middle three are a,b,c respectively. a<b<c. Also let total number of terms are 2*n + 1
What about moving to the left.
Increase in cost = (n+1)*(b-a) // numbers to the right of b ; Decrease in cost = n*(b-a) // numbers to the left of b So over all change = b-a, which is always non negative.
Similarly to the right.