BZOJ 3432: [Usaco2014 Jan]Cross Country Skiing (二分+染色法)

还是搜索~~可以看出随着D值的增大能到达的点越多,就2分d值+染色法遍历就行啦~~~

CODE:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<stack>
using namespace std;
#define maxn 510
struct node {
 int x,y;
}st;
stack<node> s;
int x[maxn][maxn],y[maxn][maxn];
bool b[maxn][maxn];
int n,m,sum;
int w[4][2]={{1,0},{-1,0},{0,-1},{0,1}};
bool check(int d){
 int t=1;
 memset(b,0,sizeof(b));
 while (!s.empty()) s.pop();
 s.push(st);
 b[st.x][st.y]=1;
 for (int i=1;i<=n;i++) b[i][0]=b[i][m+1]=1;
 for (int i=1;i<=m;i++) b[0][i]=b[n+1][i]=1;
 while (!s.empty()){
  node u=s.top ();
  s.pop();
  for (int i=0;i<4;i++)
   if (!b[u.x+w[i][0]][u.y+w[i][1]]&&abs(x[u.x+w[i][0]][u.y+w[i][1]]-x[u.x][u.y])<=d){
    b[u.x+w[i][0]][u.y+w[i][1]]=1;
    if (y[u.x+w[i][0]][u.y+w[i][1]]) {t++;if (t==sum) return 1;}
    s.push((node){u.x+w[i][0],u.y+w[i][1]});
   }
 }
 return 0;
}
int main(){
 scanf("%d%d",&n,&m);
 for (int i=1;i<=n;i++)
  for (int j=1;j<=m;j++) scanf("%d",&x[i][j]);
 for (int i=1;i<=n;i++)
  for (int j=1;j<=m;j++) {
   scanf("%d",&y[i][j]);
   if (y[i][j]) {
    sum++;
    if (st.x==0) st=(node){i,j};
   }
  }
 if (sum<=1) {printf("0");return 0;}
 int l=0,r=1000000000;
 while (l+1<r) {
  int mid=(l+r)>>1;
  if (check(mid)) r=mid;
  else l=mid;
 }
 if (check(l)) printf("%d ",l);
 else printf("%d ",r);
 return 0;
}

原文地址:https://www.cnblogs.com/New-Godess/p/4348952.html