洛谷 B4451:[GESP202512 四级] 建造 ← 二维数组

​【题目来源】
https://www.luogu.com.cn/problem/B4451

【题目描述】
小 A 有一张 M 行 N 列的地形图,其中第 i 行第 j 列的数字 a_ij  代表坐标 (i,j) 的海拔高度。
停机坪为一个 3×3 的区域,且内部所有 9 个点的最大高度和最小高度之差不超过 H。
小 A 想请你计算出,在所有适合建造停机坪的区域中,区域内部 9 个点海拔之和最大是多少。

【输入格式】
第一行三个正整数 M,N,H,含义如题面所示。
之后 M 行,第 i 行包含 N 个整数 a_i1, a_i2, … , a_iN,代表坐标 (i,j) 的高度。
数据保证总存在一个适合建造停机坪的区域。

【输出格式】
输出一行,代表最大的海拔之和。

【输入样例】
5 5 3
5 5 5 5 5
5 1 5 1 5
5 5 5 5 5
5 2 5 2 5
3 5 5 5 2

【输出样例】
40

【数据范围】
对于所有测试点,保证 1≤M, N≤10^3,1≤H, a_ij≤10^5。

【算法分析】
考查“二维数组”的应用。

【算法代码】

#include <bits/stdc++.h>
using namespace std;

const int N=1e3+5;
int a[N][N];
int ans=INT_MIN;
int n,m,h;

int main() {
    cin>>n>>m>>h;
    for(int i=1; i<=n; i++) {
        for(int j=1; j<=m; j++) {
            cin>>a[i][j];
        }
    }

    for(int i=1; i<n+3; i++) {
        for(int j=1; j<m+3; j++) {
            int minn=a[i][j];
            int maxn=a[i][j];
            int sum=0;
            for(int x=i; x<i+3; x++) {
                for(int y=j; y<j+3; y++) {
                    sum+=a[x][y];
                    minn=min(minn,a[x][y]);
                    maxn=max(maxn,a[x][y]);
                }
            }
            if(maxn-minn<=h) ans=max(ans,sum);
        }
    }
    cout<<ans<<endl;

    return 0;
}

/*
in:
5 5 3
5 5 5 5 5
5 1 5 1 5
5 5 5 5 5
5 2 5 2 5
3 5 5 5 2

out:
40
*/






【参考文献】
https://blog.csdn.net/guolianggsta/article/details/156422414
https://mp.weixin.qq.com/s/2APpGwyKABdSi83eO3harA


 

​

posted @ 2026-01-03 20:50  Triwa  阅读(323)  评论(0)    收藏  举报