【BZOJ】1104: [POI2007]洪水pow

题意

给一个\(n * m(1 \le n, m \le 1000)\)的矩阵,如果\(a_{i, j}\)为正表示城市。\(|a_{i, j}|(|a_{i, j}| \le 1000)\)是格子\((i, j)\)的海拔。现在需要放最少的抽水机,使得把所有城市的水都抽干。自行脑部抽水机是怎么工作的。

分析

容易发现:

  1. 存在最优解使得抽水机都放在城市中。
  2. 一定是从海拔低的城市开始放。

题解

根据传递性,在\((i, j)\)放了抽水机,如果上下左右有海拔比自己高的(或等于),则那个格子也相当于放了一个抽水机。
由于高度不超过1000,所以我们类似bfs一样从低到高一层层拓展即可。由于我们需要先考虑城市的抽水机,所以我们需要开两个队列来维护没拓展的点。

#include <bits/stdc++.h>
using namespace std;
inline int getint() {
	int x=0, f=1, c=getchar();
	for(; c<48||c>57; f=c=='-'?-1:f, c=getchar());
	for(; c>47&&c<58; x=x*10+c-48, c=getchar());
	return x*f;
}
const int N=1005, dx[]={1, -1, 0, 0}, dy[]={0, 0, 1, -1};
int a[N][N], c[N][N], n, m, mx;
struct id {
	int x, y;
};
vector<id> top1[N], top2[N];
void extend(int x, int y) {
	for(int k=0; k<4; ++k) {
		int fx=x+dx[k], fy=y+dy[k];
		if(fx<1 || fy<1 || fx>n || fy>m || c[fx][fy]!=-1) {
			continue;
		}
		c[fx][fy]=max(c[x][y], a[fx][fy]);
		top2[c[fx][fy]].push_back((id){fx, fy});
	}
}
int main() {
	n=getint(), m=getint();
	for(int i=1; i<=n; ++i) {
		for(int j=1; j<=m; ++j) {
			a[i][j]=getint();
			c[i][j]=-1;
			if(a[i][j]>0) {
				top1[a[i][j]].push_back((id){i, j});
				mx=max(mx, a[i][j]);
			}
			else {
				a[i][j]=-a[i][j];
			}
		}
	}
	int ans=0;
	for(int i=1; i<=mx; ++i) {
		for(;;) {
			if(top2[i].size()) {
				int x=top2[i].back().x, y=top2[i].back().y;
				top2[i].pop_back();
				extend(x, y);
			}
			else if(top1[i].size()) {
				int x=top1[i].back().x, y=top1[i].back().y;
				top1[i].pop_back();
				if(~c[x][y]) {
					continue;
				}
				++ans;
				c[x][y]=a[x][y];
				extend(x, y);
			}
			else {
				break;
			}
		}
	}
	printf("%d\n", ans);
	return 0;
}
posted @ 2015-11-22 13:05  iwtwiioi  阅读(453)  评论(0编辑  收藏  举报