题目链接:
https://www.luogu.org/problem/show?pid=2658
题意:
题解:
二分D,BFS判断是否可以到达全部路标。
很有道理啊,为什么T啊!
代码:
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 #define MS(a) memset(a,0,sizeof(a)) 5 #define MP make_pair 6 #define PB push_back 7 const int INF = 0x3f3f3f3f; 8 const ll INFLL = 0x3f3f3f3f3f3f3f3fLL; 9 inline ll read(){ 10 ll x=0,f=1;char ch=getchar(); 11 while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} 12 while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} 13 return x*f; 14 } 15 // 16 const int maxn = 500+10; 17 18 int n,m,sx,sy,sum; 19 int G[maxn][maxn],is_p[maxn][maxn],vis[maxn][maxn]; 20 int dx[4] = {0,0,1,-1}; 21 int dy[4] = {1,-1,0,0}; 22 23 struct node{ 24 int x,y; 25 }; 26 27 bool ok(int x,int y){ 28 return x>=1 && x<=n && y>=1 && y<=m && !vis[x][y]; 29 } 30 31 bool check(int x){ 32 MS(vis); 33 queue<node> q; 34 q.push(node{sx,sy}); vis[sx][sy] = 1; 35 int cnt = 1; 36 while(!q.empty()){ 37 node now = q.front(); q.pop(); 38 for(int i=0; i<4; i++){ 39 int tx=now.x+dx[i]; 40 int ty=now.y+dy[i]; 41 if(ok(tx,ty) && abs(G[tx][ty]-G[now.x][now.y]) <= x){ 42 vis[tx][ty] = 1; 43 q.push(node{tx,ty}); 44 cnt += is_p[tx][ty]; 45 if(cnt == sum) return true; 46 } 47 } 48 } 49 // return cnt == sum; 50 return false; 51 } 52 53 int main(){ 54 n=read(),m=read(); 55 int mi=INF,mx=-1; 56 for(int i=1; i<=n; i++) 57 for(int j=1; j<=m; j++){ 58 G[i][j]=read(); 59 mi=min(mi,G[i][j]); 60 mx=max(mx,G[i][j]); 61 } 62 for(int i=1; i<=n; i++) 63 for(int j=1; j<=m; j++){ 64 is_p[i][j]=read(); 65 sum += is_p[i][j]; 66 if(is_p[i][j]) sx=i,sy=j; 67 } 68 69 int L=0,R=mx-mi,ans=0; 70 while(L<=R){ 71 int mid = (L+R)/2; 72 if(check(mid)) ans=mid,R=mid-1; 73 else L=mid+1; 74 } 75 76 cout << ans << endl; 77 78 return 0; 79 }