Test instructions
There is a place between China and India, this place is abstracted, so it can be regarded as an n * M matrix, in which the black represents the mountain can not go past, the white represents the plain, can pass, the person can choose to move up and down four direction each time, but with the change of time certain white Plains will become Black mountains, Thus become impassable, the topic is given a figure representing the topography, and then there is a Q operation, the first operation of the representative in the year I (x, y) at the plains into a mountain, that white into black. Ask China India The earliest completely cut off time, if after Q years have not cut off on output-1;
Ideas:
For the 0-q year, the two points are then used to determine connectivity using the DFS piece lift point. If the isolation has been formed in the mid year, then the answer is between [Lo-mid], continue two points, otherwise the answer is between (Mid,hi). You do not need to restore the original image when backtracking, because each point only needs to determine the connectivity.
Code:
#include <cstdio>#include<iostream>#include<cstring>#include<cstring>#include<cmath>#include<cstdlib>#include<algorithm>using namespacestd;intBeginX, BeginY;intStepx[] = {0,0, -1,1};//each selectable directionintStepy[] = {-1,1,0,0};intdate[503][503];intgra[503][503];intFlag;intN, M;intCheckintXinty) {//can go to x, y dotif(Gra[x][y] = =-2|| Gra[x][y] = =1|| Gra[x][y] = =-1) return 0; return 1;}voidBacktrackintXinty) { if(x = =N)//Go to the bottom, figure connect flag=1; Else{ for(inti =0; I <=3; i++){ inttx = x +Stepx[i]; intTy = y +Stepy[i]; if(Check (TX, Ty)) {Gra[tx][ty]= -2;//has passedif(flag)return; Backtrack (TX, ty);//backtracking continues to solve} }}}structpoint{intx; inty;} point[250007];intIsOk (intmid) {memcpy (Gra, date,sizeof(date)); for(intj =1; J <= Mid; J + +) gra[point[j].x] [point[j].y]=1; for(inti =1; I <= M; i++){ if(gra[1][i]! =1) {BeginY=i; BeginX=1; Flag=0; Backtrack (1, i); if(Flag = =1)return 0; } } return 1;}intMain () {//freopen ("In.txt", "R", stdin); intT; scanf ("%d",&T); while(t--) {memset (date,-1,sizeof(date)); scanf ("%d%d", &n, &M); for(inti =1; I <= N; i++) for(intj =1; J <= M; J + +) scanf ("%1d",&Date[i][j]); intQ; scanf ("%d",&p); for(inti =1; I <= Q; i++){ intb; scanf ("%d%d", &a, &b); point[i].x= A +1; Point[i].y= B +1; } if(IsOk (Q) = =0) {printf ("-1\n");Continue;} intLo =0; intfin=Q; intAns =-1; while(Lo <=hi) {//two-point solution yes_leftintMid = lo + (hi-lo)/2; if(IsOk (mid)) Hi = mid-1; ElseLo = mid +1; } printf ("%d\n", lo); } return 0;}
HDU 5652 India and China origins (two points + DFS)