关于#平面#的问题,如何解决?

Description

勘察队发现一块M*N的土地,通过勘察得到每一处的海平面高度。

现在队长需要你统计每一海平面高度对应的面积

并且想把高处的土填到低洼处,需要你求出填平后平均海拔,如果填不平输出-1(即总海拔值小于0)
Input

第一行有两个数M和N(0 < M, N < 1000)

第2~M+1行,每行有N列,代表对应点的海拔(-300 < 海拔 < 400)
Output

输出K行,每行代表对应海拔的面积,海拔和面积中间使用空格间隔(按海拔升序输出,对应海拔无面积不需要输出)

最后一行输出填平后的平均海拔(取整),填不平输出-1
Sample Input
2 3
-5 5 15
-5 0 5
Sample Output
-5 2
0 1
5 2
15 1
2

有思路,望解答

基于Monster 组和GPT的调写:
用深度优先搜索算法(DFS)来解决。具体来说,可以从每一个点出发,找到所有高度相同的区域,并计算面积和海拔值。然后,根据高度升序输出每个高度对应的面积和海拔值,最后计算填平后的平均海拔值。


#include <iostream>
#include <cstring>

using namespace std;

const int MAXN = 1005;

int m, n, land[MAXN][MAXN];
bool visited[MAXN][MAXN];
int dx[] = {0, 0, 1, -1};  // 右、左、下、上
int dy[] = {1, -1, 0, 0};
int cnt[MAXN*MAXN], sum[MAXN*MAXN], num;

void dfs(int x, int y, int h) {
    visited[x][y] = true;
    cnt[num]++;
    sum[num] += land[x][y];
    for (int i = 0; i < 4; i++) {
        int nx = x + dx[i], ny = y + dy[i];
        if (nx >= 1 && nx <= m && ny >= 1 && ny <= n && !visited[nx][ny] && land[nx][ny] == h) {
            dfs(nx, ny, h);
        }
    }
}

int main() {
    cin >> m >> n;
    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            cin >> land[i][j];
        }
    }
    memset(visited, false, sizeof(visited));
    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            if (!visited[i][j]) {
                num++;
                dfs(i, j, land[i][j]);
            }
        }
    }
    for (int i = -300; i <= 400; i++) {
        int area = 0, height = 0;
        for (int j = 1; j <= num; j++) {
            if (sum[j] / cnt[j] == i) {
                area += cnt[j];
                height += sum[j];
            }
        }
        if (area > 0) {
            cout << i << " " << area << endl;
        }
    }
    int total = 0;
    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            total += land[i][j];
        }
    }
    if (total < 0) {
        cout << "-1" << endl;
    } else {
        cout << total / (m*n) << endl;
    }
    return 0;
}

img

也可以用一个数组,或者用map容器,保存不同海拔的面积,遍历m*n的土地,将土地高度对应的面积加1。
代码:

#include<iostream>
#include<map>
using namespace std;

map<int,int>cnt;

int main(){
    int m,n,i,j,h,total = 0;
    map<int,int>::iterator it;
    cin>>m>>n;
    for(i=0;i<m;i++){
        for(j=0;j<n;j++){
            cin>>h;
            cnt[h]++;
        }
    }
    for(it=cnt.begin();it!=cnt.end();it++){
        cout<<it->first<<" "<<it->second<<endl;
        total+=it->first*it->second;
    }
    if (total < 0) {
        cout << "-1" << endl;
    } else {
        cout << total / (m*n) << endl;
    }
    return 0;
}

执行结果

img