[P2658]汽车拉力比赛

原题链接

二分

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<queue>
#include<vector>
#include<climits>
#include<string>
#include<cstdlib>
#include<ctime>
#define LL long long
#define MOD 1000000007
#define pi 3.141592653589
using namespace std;

int dx[5]={0,1,0,-1,0},dy[5]={0,0,1,0,-1};
int n,m,i,j,h[505][505],l,r,maxn,minn,cnt,mid,mark[505][505],f[505][505],x[250005],y[250005],mx,my;

bool check(int d)
{
    int head,tail,tot=1,xx,yy;

    memset(f,0,sizeof(f));

    head=1;
    tail=1;
    x[1]=mx;
    y[1]=my;
    f[y[1]][x[1]]=1;

    while(head<=tail)
    {
        if(tot==cnt) return true;

        for(i=1;i<=4;i++)
        {
            xx=x[head]+dx[i];
            yy=y[head]+dy[i];           

            if((!f[yy][xx])&&(abs(h[yy][xx]-h[y[head]][x[head]])<=d)&&(xx<=n)&&(xx>=1)&&(yy<=m)&&(yy>=1))
            {
                tail++;
                x[tail]=xx; 
                y[tail]=yy;
                f[yy][xx]=1;
                if(mark[yy][xx]==1) tot++;
            }
        }

        head++;
    }

    return false;
}

int main()
{
    scanf("%d%d",&m,&n);

    for(i=1;i<=m;i++)
        for(j=1;j<=n;j++)
        {
            scanf("%d",&h[i][j]);
            maxn=max(maxn,h[i][j]);     
        }

    r=maxn;
    l=0;

    for(i=1;i<=m;i++)
        for(j=1;j<=n;j++)
        {
            scanf("%d",&mark[i][j]);    

            if(mark[i][j]==1)
            {
                cnt++;

                if(cnt==1)
                {
                    my=i;
                    mx=j;                   
                }
            }       
        }

    while(l<=r)
    {
        mid=(l+r)>>1;

        if(check(mid)) r=mid-1;
        else l=mid+1;
    }

    printf("%d",l);

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值