1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| const int MAX=500+10; int n,m,a[MAX][MAX],g[MAX][MAX],ans=0,sum,fx,fy; int vis[MAX][MAX]; int aw[4][2]={-1,0,0,1,1,0,0,-1}; struct node{ int x,y; node(int _x,int _y){ x=_x;y=_y; } }; bool judge(int x,int y){ if(x<1 || x>n ||y<1 ||y>m) return false; return true; } inline bool bfs(int d){ int cnt =0; queue<node>q; q.push(node(fx,fy)); vis[fx][fy]=d; while(!q.empty()){ node t= q.front(); q.pop(); cnt += g[t.x][t.y]; if(cnt == sum) return true; fi(i,0,4){ int tx = t.x +aw[i][0],ty = t.y +aw[i][1]; if(judge(tx,ty) && vis[tx][ty] != d && abs(a[t.x][t.y] - a[tx][ty]) <= d){ vis[tx][ty] = d; q.push(node(tx,ty)); } } } return false; } int main(){ freopen("in","r",stdin); sf(n);sf(m); mem(vis,0); int _max=0; fi(i,1,n+1) fi(j,1,m+1){ sf(a[i][j]); _max=max(_max,a[i][j]); } fi(i,1,n+1) fi(j,1,m+1){ sf(g[i][j]); if(g[i][j]) { sum ++; if(sum==1) { fx = i;fy =j; } } } int l = 0,r=_max; while(l<=r){ int m =(l+r)/2; if(bfs(m)){ ans = m; r= m-1; }else l=m+1; } pf(ans); return 0; }
|