TOMGRID - Editorial

Contest Link: THE CODETRIX
Problem Link : TOMGRID
Author : shyam1909
Difficulty Level : Cakewalk

Understanding the Statement:

  1. We are given a grid. Each square in the grid has some number of blocks in it.
  2. We are required to find the minimum total number of blocks that has to be removed from the grid, so that all blocks in the grid would have equal number of blocks.

Solution:
The number of total blocks that has to be removed from the grid should be minimal.
So, we find the square which has the least number of blocks. Let the number of blocks in that square be min .
Now, we decide to make the number of blocks in all individual squares equal to min . The excess blocks are removed.
The total sum of the excess blocks is the required answer.

CODE:

#include<bits/stdc++.h>
using namespace std;
#define INF 2147483647;
void solve()
{
int r,c;
cin >> r >> c;
int arr[r][c];
int min = INF;
for(int i=0; i<r; i++){
for(int j=0; j<c; j++){
cin >> arr[i][j];
if(arr[i][j] <= min){
min = arr[i][j];
}
}
}
long long int count = 0;
for(int i=0; i<r; i++){
for(int j=0; j<c; j++){
count += (arr[i][j] - min);
}
}
cout << count << endl;
}
int main()
{
int t;
cin >> t;
for(int i = 1;i <= t; i++){
solve();
}
return 0;
}