HDU 5652
二分,对于一个区域划分为AB,如果要求的值为A中的最大值,应用左闭右开。如果要求的值为B中的最小值,应用左开又闭。
#include<cstdio>
#include<cstring>
const int maxn = 510;
struct Node{
int x, y;
}op[maxn * maxn];
int map[maxn][maxn], vis[maxn][maxn];
int d[][4] = {1, 0, -1 , 0, 0, -1, 0, 1};
int n, m;
char s[maxn];
void Set(int now, int will){
if(now < will)
for(int i = now+1; i <= will; i++)
map[op[i].x][op[i].y] = true;
else
for(int i = now; i > will; i--)
map[op[i].x][op[i].y] = false;
}
bool cango(int x, int y){
if(x < 0 || x >= n || y < 0 || y >= m) return false;
else return true;
}
bool DFS(int x, int y){
if(!cango(x, y)) return false;
if(map[x][y] || vis[x][y]) return false;
if(x == n-1) return true;
vis[x][y] = true;
for(int i = 0; i < 4; i++)
if(DFS(x+d[0][i], y+d[1][i])) return true;
return false;
}
bool is_connect(){
memset(vis, 0, sizeof(vis));
for(int i = 0; i < m; i++)
if(DFS(0, i)) return true;
return false;
}
int main(){
// freopen("in.txt", "r", stdin);
int T; scanf("%d", &T);
while(T--){
scanf("%d%d", &n, &m);
for(int i = 0; i < n; i++){
scanf("%s", s);
for(int j = 0; j < m; j++)
map[i][j] = s[j] == '0' ? 0 : 1;
}
int q; scanf("%d", &q);
for(int i = 1; i <= q; i++)
scanf("%d%d", &op[i].x, &op[i].y);
int l = -1, r = q+1, now = 0;
while(r - l > 1){
int m = (l + r) / 2;
// printf("m:%d\n", m);
Set(now, m);
now = m;
if(is_connect()) l = m;
else r = m;
}
printf("%d\n", r == q+1 ? -1 : r);
}
return 0;
}
用并查集也可以做?