what is logic behind formula of One more weird game question

i was trying One more weird game Question of codechef, when i didn’t get the logic even after thinking a lot. i saw some submitted answers. and i notice that all people are using one formula 2mn-m-n in their code. can someone explain me where this formula come from, Derivation of this formula, logic behind this formula because this formula doesn’t came out of nowhere their should be some logic behind this formula.

Initially,try to fill some rectangular grid (of random dimension) considering score. After two to three egs you will find a pattern of score that goes this way:


0 1 1 1 1 1 … //first row

1 2 2 2 2 2 …… //Second row

1 2 2 2 2 2……

…………. // nth row


I considered coloring in sequence from L->R and top -> Bottom . If you will change order of filling the color then only digits will get shuffled but actual digit value is going to remain same for given N*M dimension(as per above diagram). So u can use formula for overall sum calculation.

So now You can very well guess sum of this elements for N*M order will be 2MN-M-N.

Thanks Bro
You Really helped a lot
just one more doubt regarding this question, is the value of score remain same (constant) irrespective of order of filling blocks ?

yeah u can try it bcoz only the pattern changes while value of digit remains same