题意:n*m的地图, 每个格子有一个海拔高度, 海拔<0的地方有水, 现在在(x, y)最深处放一个抽水机, 问最多能抽多少水, 水只能从高出往低处流
解题思路:一开始我用了类似spfa的思路,不过有数据点超时了,后来改为优先队列, 保证先出队列的是当前已处理的最深的节点
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <vector>
#include <bitset>
#include <functional>
using namespace std;
#define LL long long
const int INF = 0x3f3f3f3f;
int n, m, x, y;
int a[505][505];
int vis[505][505],h[505][505];
int dir[8][2] = { {1,0},{0,1},{0,-1},{-1,0},{1,1},{-1,-1},{1,-1},{-1,1} };
struct node
{
int x, y, h;
bool operator<(const node &a)const
{
return h > a.h;
}
}pre, nt;
int main()
{
while (~scanf("%d%d", &n, &m))
{
priority_queue<node>q;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) scanf("%d", &a[i][j]);
scanf("%d%d", &x, &y);
memset(vis, 0, sizeof vis);
pre = { x,y,a[x][y] };
q.push(pre);
vis[x][y] = 1;
h[x][y] = a[x][y];
while (!q.empty())
{
pre = q.top();
q.pop();
for (int i = 0; i < 8; i++)
{
int xx = pre.x + dir[i][0];
int yy = pre.y + dir[i][1];
if (xx<1 || yy<1 || xx>n || yy>m|| a[xx][yy] >= 0||vis[xx][yy]) continue;
int tmp = max(pre.h, a[xx][yy]);
h[xx][yy] = tmp;
vis[xx][yy] = 1;
nt = { xx,yy,tmp };
q.push(nt);
}
}
LL ans = 0;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
ans += -1LL * h[i][j];
printf("%lld\n", ans);
}
return 0;
}