Блог пользователя codeshaker

Автор codeshaker, 11 лет назад, По-английски
  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

»
11 лет назад, # |
  Проголосовать: нравится +1 Проголосовать: не нравится

You're trying to divide candies on piles and each pile should contain some candies. For each missing candy you obtain some anger and you want to minimaze total amount of anger. First logical question is: "Is better to keep one pile full and other almost empty, or trying to balanced it, so each pile missing some number of candies?"

The answer is simple, when you write it down. Imagine two piles. First pile is missing x candies, second is missing x+k candies for some positive k. Amount of anger is x^2 + (x+k)^2 = 2(x^2) + 2xk + k^2.

Now take one candy from bigger pile (with only x candies missing) and take it on second pile. You missing x+1 candies on first and x+k-1 candies on second pile. The amount of anger is (x+1)^2 + (x+k-1)^2 and when we multiply brackets it's equal to 2(x^2) + 2xk + k^2 -2k + 2. So total amount of anger decreased, when we balanced number of missing candies on piles.

So solution is clear now. We want to divide candies in such manner, that on each pile number of missing candies is equal (or may differ by 1).

The easiest and the fastest way to find number of missing candies on each pile is use binary search. If we want r candies missing everywhere, we should find out, if sum of all piles minus r for each of them (maybe even less than r, if pile is not big enough) is less or equal than M — total number of candies.

When we find optimal (as small as possible) value of r just fairly distribute all candies between piles. And you've got it :)

I think, that hardest part is to realize, that you want to balance number of missing candies on each pile. After this, it's pretty easy.

  • »
    »
    11 лет назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    i dont think ur approach works correctly if there exists a pile with less than r candies initially.
    i think this was the case on which i got WA.

»
11 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

thnx @monsterspy it was a great explanation, got the logic!!