2014 UESTC Training for Search Algorithm I

本文介绍了一种使用二分查找算法解决寻找最近两个兵团之间的最大距离问题的方法。通过不断调整距离阈值并验证其可行性来逼近最优解。
要求求最近两个最近兵团距离的最大值,思路就是二分这个最大值
根据谓词p判断当前给予的这个最大值是否能够满足条件(<=M)
不断二分答案直到终点输出答案就可以
判断谓词p的方法是从首位开始枚举i,然后以j从i+1开始遍历每次找到两距离差小于当前判断mid值时count++;

一旦>-当前mid.那么i从j开始乡下遍历。最终根据count判断谓词

#include <map>
#include <set>
#include <list>
#include <cmath>
#include<cctype>
#include <ctime>
#include <deque>
#include <stack>
#include <queue>
#include <cstdio>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#define LL long long
#define PI 3.1415926535897932626
using namespace std;
int gcd(int a, int b)
{
	return a % b == 0 ? b : gcd(b, a % b);
}
#define MAXN 50010
LL src[MAXN];
LL res[MAXN];
LL X,N,M;
LL MAX,MIN;
void init()
{
    for (int i=1;i<=N;i++)
        scanf("%lld",&src[i]);;
    MIN=src[0]=0;
    MAX=src[N+1]=X;
    sort(src,src+N+2);
    //printf("%lld %lld\n",MIN,MAX);
   // for (int i=0;i<=N+1;i++)
    //   printf("%lld ",src[i]);
  // putchar('\n');
}
int judge(int mid)
{
    int ans=0,i=0;
    //printf("%d\n",mid);
   while (i<=N)
   {   int j;
       //printf("i=%d\n",i);
       for ( j=i+1;j<=N+1;j++)
       {
           if (src[j]-src[i]<mid) ans++;
           else {i=j;break;}
       }
       if (j==N+2)break;
   }
   //225 5 2printf("%d\n",ans);
    if (ans>M) return 0;
    return 1;
}
int binary()
{
    int mid;
    while (MIN<MAX)
    {
        mid=(MAX+MIN)/2;
        if (judge(mid)==0) MAX=mid;
       else  MIN=mid+1;
    }
    //printf("%lld %lld %d\n",MIN,MAX,mid);
    return  MAX-1;
}
int main()
{
    while (scanf("%lld%lld%lld",&X,&N,&M)==3)
    {
        init();
        LL a=binary();
        printf("%lld\n",a);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值