hdu 5652 India and China Origins 二分+bfs

时间:2021-12-23 22:34:18

题目链接

给一个图, 由01组成, 1不能走。 给q个操作, 每个操作将一个点变为1, 问至少多少个操作之后, 图的上方和下方不联通。

二分操作, 然后bfs判联通就好了。

#include <iostream>
#include <vector>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <complex>
#include <cmath>
#include <map>
#include <set>
#include <string>
#include <queue>
#include <stack>
#include <bitset>
using namespace std;
#define pb(x) push_back(x)
#define ll long long
#define mk(x, y) make_pair(x, y)
#define lson l, m, rt<<1
#define mem(a) memset(a, 0, sizeof(a))
#define rson m+1, r, rt<<1|1
#define mem1(a) memset(a, -1, sizeof(a))
#define mem2(a) memset(a, 0x3f, sizeof(a))
#define rep(i, n, a) for(int i = a; i<n; i++)
#define fi first
#define se second
typedef complex <double> cmx;
typedef pair<int, int> pll;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int mod = 1e9+7;
const int inf = 1061109567;
const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
char s[505][505];
int g[505][505], f[505][505], vis[595][505], n, m;
pll a[250001];
int bfs(int x, int y) {
queue<pll> q;
q.push(mk(x, y));
vis[x][y] = 1;
while(!q.empty()) {
pll tmp = q.front(); q.pop();
if(tmp.fi == n+1)
return 0;
for(int i = 0; i < 4; i++) {
int tmpx = tmp.fi+dir[i][0];
int tmpy = tmp.se+dir[i][1];
if(tmpx>=0&&tmpx<=n+1&&tmpy>=0&&tmpy<m) {
if(vis[tmpx][tmpy]||f[tmpx][tmpy])
continue;
vis[tmpx][tmpy] = 1;
q.push(mk(tmpx, tmpy));
}
}
}
return 1;
}
int check(int x) {
memcpy(f, g, sizeof(f));
for(int i = 0; i < x; i++) {
f[a[i].fi+1][a[i].se] = 1;
}
mem(vis);
return bfs(0, 0);
}
int main()
{ int t, q, x, y;
cin>>t;
while(t--) {
scanf("%d%d", &n, &m);
for(int i = 0; i < n; i++){
scanf("%s", s[i]);
}
cin>>q;
for(int i = 0; i < q; i++) {
scanf("%d%d", &a[i].fi, &a[i].se);
}
mem(g);
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
g[i+1][j] = s[i][j]-'0';
}
}
int l = 0, r = q, ans = -1;
while(l<=r) {
int mid = l+r>>1;
if(check(mid)) {
ans = mid;
r = mid-1;
} else {
l = mid+1;
}
}
printf("%d\n", ans);
}
return 0;
}