C1LJUTNJ - Ljutnja

no tags 

Children in a kindergarten have received a large sack containing M candies. It has been decided that the candies are to be distributed among N children.

Each child has stated the number of candies that it wants. If a child isn’t given the amount of candy it wants, it will get angry. In fact it’ll get angrier for each candy it is deprived of. Some speculate that it’s anger will be equal to the square of the number of candy it is deprived of. For instance, if Mirko states that he wants 32 candies but receives only 29, he would be missing 3 candies, so his anger would be equal to 9.

Unfortunately, there is an insufficient amount of candy to satisfy all children. Therefore, the candies should be distributed in such a way that the sum of the children’s anger is minimal.


The first line contains two integers, M (1 ≤ M ≤ 2.109) and N (1 ≤ N ≤ 100 000).

The following N lines contain integers (one per line) which represent the wishes of the children. Those numbers are all strictly less than 2.109, and their sum always exceeds M.


The first and only line of output must contain the minimum sum of the children’s anger.

Note: The test cases will ensure that the result fits in a 64-bit unsigned integer: int64 in Pascal, long long in C/C++, long in Java.


5 3


10 4



hide comments
nadstratosfer: 2018-09-29 07:39:04

Fun to figure out, frustrating to implement without the code ending up ugly. Gave up on the latter bit, glad that ugly code can run fast too. Could have saved some time spent handling cases where there's enough candy for everyone by bothering to read the statement carefully though.

Dushyant Singh: 2016-05-14 13:08:36

Weak test cases. My code gives 2 for input
3 2
2 2
Correct answer = 1
Disappointed :(

Last edit: 2016-05-14 13:13:54
Dushyant Singh: 2016-04-13 10:30:18

@anonymous_: Take 3,4,2,1 candies from first, second, third and fourth respectively. They will be left with one candy each. So answer will be 4

anonymous_: 2016-04-12 11:02:19

How could the ans to 2nd tst case be 4? Shouldn't it be 8 ?

Nebojsa: 2016-02-26 19:43:01

Great problem, took me a while...

Siddharth Singh: 2016-01-24 15:52:25

Terrific Question , Loved It <3

CoNtRaDiCtIoN: 2015-04-02 19:31:20

yeah use unsigned long long int for test case : 8

LUCIFER: 2015-01-27 17:54:52

this is one hell of a question

Kriti Joshi: 2014-12-11 06:34:09

Use variable type unsigned long long int for 'sum of angers'. Worked for me to pass Test Case 8

Samuel Nacache: 2014-11-01 02:12:45

Finally, I have my revenge

Added by:Race with time
Time limit:0.366s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ASM64
Resource:COCI 2010-2011 1-st Round