题意
给出一张n*m的网格图代表城市,在每个格点修建水利设施有两种选择:1)处于第一行的格点可修蓄水厂 2)四周存在比它海拔更高且拥有公共边的,已经建有水利设施的相邻城市,可修建输水站。记第n行为干旱区。问是否能够使干旱区的城市均建有水利设施,若能,最少建多少蓄水厂,若不能,求不能建水利设施的城市数。
数据范围
n,m<=500
思路
搜索+减枝+DP
从每个第一行的点开始广搜,标记所能搜到的干旱区城市。若广搜完之后仍有干旱区城市未被标记,则无解。否则从每个点搜到的干旱区必然是一段连续的区间。(若存在不连续的区间,则不连续的点被四周的点孤立,属于无解的情况)那么问题转化为用最少的区间覆盖线段,简单DP即可。
for(int i = 1; i <= m; ++i)
for(int j = l[i]; j <= r[i]; ++j)
f[j] = min(f[j],f[l[i]-1] + 1);
Code
#include<cstdio>
#include<cstring>
#include<algorithm>
const int sm = 503;
const int sn = 250003;
const int Inf = 0x3f3f3f3f;
int n,m;
int q[sm],h[sm][sm];
struct node {
int x,y;
}que[sn],t;
struct QJ {
int l,r;
bool operator < (const QJ & oth) const {
return l != oth.l ? l < oth.l : r < oth.r;
}
}a[sm];
int xx[4] = {-1,1,0,0};
int yy[4] = {0,0,-1,1};
bool ex[sm];
bool vis[sm][sm];
int Max(int x,int y) { return x>y?x:y; }
void Chkmin(int &x,int y) { x = y < x ? y : x; }
void Chkmax(int &x,int y) { x = y > x ? y : x; }
bool chk(int a,int b,int x,int y) {
if(1<=x&&x<=n&&1<=y&&y<=m) {
if(h[a][b] > h[x][y]) return true;
}
return false;
}
void Bfs(int u,int v) {
int head = 0, tail = 0;
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= m; ++j)
vis[i][j] = 0;
que[++tail] = (node) { u,v };
vis[u][v] = 1;
while(head < tail) {
t = que[++head];
if(t.x == n) {
ex[t.y] = 1;
Chkmin(a[v].l,t.y);
Chkmax(a[v].r,t.y);
}
for(int i = 0; i < 4; ++i)
if(chk(t.x,t.y,t.x+xx[i],t.y+yy[i]) && !vis[t.x+xx[i]][t.y+yy[i]]) {
vis[t.x+xx[i]][t.y+yy[i]] = 1;
que[++tail] = (node) {t.x+xx[i],t.y+yy[i]};
}
}
}
int main() {
freopen("1.in","r",stdin);
scanf("%d%d",&n,&m);
for(int i = 1; i <= n; ++i)
for(int j = 1;j <= m; ++j)
scanf("%d",&h[i][j]);
for(int i = 1; i <= m; ++i) {
a[i].l = Inf, a[i].r = -1;
if(h[1][i-1] <= h[1][i] && h[1][i] >= h[1][i+1])
Bfs(1,i);
}
int cnt = 0;
for(int i = 1; i <= m; ++i)
if(!ex[i]) ++cnt;
if(cnt) printf("0\n%d\n",cnt);
else {
std::sort(a+1,a+m+1);
int k,to, R = 0, ans = 0;
for(int i = 1; i <= m; ++i) {
if(a[i].r <= R) continue;
k = i,to = 0;
while(a[k].l <= R+1)
to = Max(to,a[k++].r);
R = to, ans++;
}
printf("1\n%d\n",ans);
}
return 0;
}