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.
№ | Пользователь | Рейтинг |
---|---|---|
1 | tourist | 3993 |
2 | jiangly | 3743 |
3 | orzdevinwang | 3707 |
4 | Radewoosh | 3627 |
5 | jqdai0815 | 3620 |
6 | Benq | 3564 |
7 | Kevin114514 | 3443 |
8 | ksun48 | 3434 |
9 | Rewinding | 3397 |
10 | Um_nik | 3396 |
Страны | Города | Организации | Всё → |
№ | Пользователь | Вклад |
---|---|---|
1 | cry | 167 |
2 | Um_nik | 163 |
3 | maomao90 | 162 |
3 | atcoder_official | 162 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 155 |
8 | TheScrasse | 154 |
9 | Dominater069 | 153 |
10 | nor | 152 |
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.
Название |
---|
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.