基于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;
}