bsoj 1872-用水填坑

bsoj 1872-用水填坑

Description

现有一块n*m的地,每块1*1的地的高度为h[i,j],在n*m的土地之外的土地高度均为0(即你可以认为最外圈无法积水)
现在下了一场足够大的雨,试求出这块地总共积了多少单位体积的水

Input

第一行两个数 n, m,具体含义见题意
接下来 n 行每行m个数, 第i行为h[i,1], h[i,2], ..., h[i,m]

Output

输出一行一个数表示积水的总量

Sample Input

【输入样例1】
5 5
0 0 5 0 0
0 4 3 8 2
9 5 7 2 7
1 9 6 5 4
1 0 0 6 2

【输入样例2】
10 10
0 0 0 0 0 0 0 0 0 0
0 5 2 6 4 3 1 7 8 0
0 6 4 2 3 5 1 4 6 0
0 3 6 4 1 2 4 7 8 0
0 2 5 5 1 2 3 4 4 0
0 2 3 1 5 4 4 1 4 0 
0 4 1 2 3 4 5 2 1 0
0 7 5 5 1 5 4 5 7 0
0 1 3 5 5 4 6 8 7 0
0 0 0 0 0 0 0 0 0 0

Sample Output


【输出样例1】
4

【输出样例2】
23

Hint

【数据范围】
对于10%的数据, n, m≤4,h≤5;
对于前50%的数据, n, m≤20, h≤10;
对于前70%的数据, n, m≤100, h≤50;
对于另外10%的数据, 不存在两个连续的块能积水;
对于95%的数据, n, m≤500, h≤100.
对于100%的数据, n, m≤1000, h≤1000,000,000.

方法如下:

用堆
每次找堆中最小的看能不能更新四联通的格子
如果这个格子比他小,则可以注水(因为比当前最小的都小了)
如果比他大,就入队并标记(不然会死),因为不可形成水洼了
刚开始的时候所有的边界入队if(i==1||j==1||i==n||j==m)
巧妙的地方:可以用h刚开始等于a数组,
对于高度直接取max(就相当于判断能否注水了)
最后ans+=h[i][j]-a[i][j]即可
总而言之:相当于从外面往里面收边界!!!!!

ac代码如下:

//我贪得无厌,想要你的全部
//——许墨
#pragma GCC optimize(6)
#include
#include
#include
#include
#include
#include
#include
#include
#define maxn 1005
#define ll long long
#define love_xumo_forever main
using namespace std;
int dx[4]= {1,0,-1,0},dy[4]= {0,1,0,-1};
ll a[maxn][maxn],h[maxn][maxn];//原来的高度,可以积水的高度
bool bj[maxn][maxn];
struct que {
	int x,y;
	ll d;
};
bool operator <(que a,que b) {
	return a.d>b.d;//小根堆
}
priority_queue  q;
int read() {
	int a=0,b=1;
	char ch=getchar();
	while(ch<'0'||ch>'9') {
		if(ch=='-')b=-1;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9') a=a*10+ch-'0',ch=getchar();
	return a*b;
}
int love_xumo_forever() {
	int n,m,i,j;
	ll ans=0;
    n=read(),m=read();
	for(i=1; i<=n; i++)
		for(j=1; j<=m; j++) {
			a[i][j]=read();
			h[i][j]=a[i][j];//巧妙的h
			if(i==1||j==1||i==n||j==m) {//初始化边界
				bj[i][j]=true;
				q.push((que) {
					i,j,a[i][j]
				});
			}
		}
	while(!q.empty()) {
		int x,y,nx,ny;
		ll d;
		x=q.top().x,y=q.top().y,d=q.top().d;
		q.pop();
		for(i=0; i<4; i++) {
			nx=x+dx[i],ny=y+dy[i];
			if(nx<1||ny<1||nx>n||ny>m||bj[nx][ny]) continue;
			bj[nx][ny]=true;//不要忘了!!
			h[nx][ny]=max(h[nx][ny],d);
			q.push((que) {
				nx,ny,h[nx][ny]//一定是h入队(相当于一个个填平)
			});
		}
	}
	for(i=1; i<=n; i++)
		for(j=1; j<=m; j++) ans+=(ll)h[i][j]-a[i][j];
	printf("%lld\n",ans);
	return 0;
}

你可能感兴趣的:(堆)