AtCoder题解 —— AtCoder Beginner Contest 186 —— B - Blocks on Grid

题目相关

题目链接

AtCoder Beginner Contest 186 B 题,https://atcoder.jp/contests/abc186/tasks/abc186_b

Problem Statement

We have a grid with H horizontal rows and W vertical columns. The square at the i-th row from the top and j-th column from the left has A i , j A_{i,j} Ai,j blocks stacked on it.
At least how many blocks must be removed to make all squares have the same number of blocks?

Input

Input is given from Standard Input in the following format:

H W
A1,1 A1,2 … A1,W
⋮
AH,1 AH,2 … AH,W

Output

Print the minimum number of blocks that must be removed.

Sample 1

Sample Input 1

2 3
2 2 3
3 2 2

Sample Output 1

2

Explaination

Removing 1 block from the top-right square and 1 from the bottom-left square makes all squares have 2 blocks.

Sample 2

Sample Input 2

3 3
99 99 99
99 0 99
99 99 99

Sample Output 2

792

Sample 3

Sample Input 3

3 2
4 4
4 4
4 4

Sample Output 3

0

Constraints

  • 1 ≤ H, W ≤ 100
  • 0 ≤ Ai,j ≤ 100

题解报告

题目翻译

我们有一个水平为 H,垂直为 W 的格子,问需要从这些格子中删除多少数字,才能使得每个格子的数据一样。

题目分析

又是一个非常友善的问题。通过读题目,我们就知道答案。只需要找出矩阵的最小值,然后将矩阵的非最小值元素变成最小值,这些差的总和就是答案。
因此本题的核心是遍历矩阵,寻找最小值。找到最小值后,再次遍历矩阵,计算答案。

数据范围估计

最大规模的矩阵为 100*100,也就是 1e4 个数据,数据的最大值为 100,最小值为 0,因此最大的总和为 ( 1 0 4 − 1 ) ∗ 100 ≈ 1 0 6 (10^4-1)*100\approx10^6 (1041)100106,因此用 int 表示就可以了。

AC 参考代码

//https://atcoder.jp/contests/abc186/tasks/abc186_b
//B - Blocks on Grid
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
 
//#define __LOCAL
 
const int MAXN=1e2+4;
int a[MAXN][MAXN];
 
int main() {
    
    
#if !defined(__LOCAL)
    cin.tie(0);
    ios::sync_with_stdio(false);
#endif
    int h,w;
    cin>>h>>w;
    int minx=MAXN;
    for (int i=1; i<=h; i++) {
    
    
        for (int j=1; j<=w; j++) {
    
    
            cin>>a[i][j];
            minx = min(a[i][j], minx);
        }
    }
 
    int ans=0;
    for (int i=1; i<=h; i++) {
    
    
        for (int j=1; j<=w; j++) {
    
    
            ans += (a[i][j]-minx);
        }
    }
 
    cout<<ans<<"\n";
 
    return 0;
}

在这里插入图片描述

时间复杂度

O(HW)。

空间复杂度

O(HW)。

猜你喜欢

转载自blog.csdn.net/justidle/article/details/111412269