感觉自己什么题都写不动了。
又是一个神贪心:把所有城市中的点按照高度从小到大排序之后拿出来逐个计算,枚举其他高度小于它的点向四周扩展,如果这个点不能被之前放过的抽水机覆盖,那么把答案加一,并在这个点放上一台抽水机。这个过程适合用并查集来维护。
非常懒的我把地图周围一圈都赋值为无限大。
这样子保证了城市中的所有点能够被最小代价地覆盖。
时间复杂度$O(nm log nm)$,有点卡常。
Code:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int N = 1005; const int dx[] = {1, 0, -1, 0}; const int dy[] = {0, 1, 0, -1}; const int inf = 1 << 30; int n, m, tot = 0, a[N][N], ufs[N * N]; bool vis[N * N]; struct Node { int x, y, val; friend bool operator < (const Node &u, const Node &v) { return u.val < v.val; } } b[N * N], c[N * N]; inline void read(int &X) { X = 0; char ch = 0; int op = 1; for(; ch > '9'|| ch < '0'; ch = getchar()) if(ch == '-') op = -1; for(; ch >= '0' && ch <= '9'; ch = getchar()) X = (X << 3) + (X << 1) + ch - 48; X *= op; } inline int id(int x, int y) { return (x - 1) * m + y; } int find(int x) { return ufs[x] == x ? x : ufs[x] = find(ufs[x]); } inline void merge(int x, int y) { int fx = find(x), fy = find(y); if(fx == fy) return; ufs[fx] = fy; if(vis[fx]) vis[fy] = 1; } inline void ext(int x, int y) { for(int i = 0; i < 4; i++) { int tox = x + dx[i], toy = y + dy[i]; if(a[tox][toy] <= a[x][y]) merge(id(tox, toy), id(x, y)); } } int main() { read(n), read(m); for(int i = 1; i <= n; i++) for(int j = 1; j <= m; j++) { read(a[i][j]); if(a[i][j] > 0) c[++tot] = (Node) {i, j, a[i][j]}; else a[i][j] *= -1; b[id(i, j)].x = i, b[id(i, j)].y = j, b[id(i, j)].val = a[i][j]; ufs[id(i, j)] = id(i, j); } for(int i = 0; i <= m + 1; i++) a[0][i] = a[n + 1][i] = inf; for(int i = 0; i <= n + 1; i++) a[i][0] = a[i][m + 1] = inf; sort(b + 1, b + 1 + n * m); sort(c + 1, c + 1 + tot); /* for(int i = 1; i <= tot; i++) printf("%d %d %d ", c[i].x, c[i].y, c[i].val); */ int ans = 0; for(int j = 1, i = 1; i <= tot; i++) { for(; j <= n * m && c[i].val >= b[j].val; j++) ext(b[j].x, b[j].y); int now = find(id(c[i].x, c[i].y)); if(!vis[now]) { vis[now] = 1; ans++; } } printf("%d ", ans); return 0; }