【基础算法练习题】蓄水池问题
2024年12月24日小于 1 分钟
#include <bits/stdc++.h>
#define int long long
using namespace std;
int n;
int a[305][305];
// first -高度,second 位置
priority_queue<pair<int, pair<int, int>>> q;
bool vis[305][305];
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
{
cin >> a[i][j];
if (i == 1 || j == 1 || i == n || j == n)
{
vis[i][j] = true;
q.push(make_pair(-a[i][j], make_pair(i, j)));
}
}
int ans = 0;
while (!q.empty())
{
auto now = q.top();
q.pop();
int height = -now.first;
int x = now.second.first;
int y = now.second.second;
for (int fx = 0; fx < 4; fx++)
{
int nx = x + dx[fx];
int ny = y + dy[fx];
if (nx < 1 || nx > n || ny < 1 || ny > n || vis[nx][ny])
continue;
if (height > a[nx][ny])
{
ans += height - a[nx][ny];
a[nx][ny] = height;
}
vis[nx][ny] = true;
q.push(make_pair(-a[nx][ny], make_pair(nx, ny)));
}
}
cout << ans << "\n";
return 0;
}