codevs2072 分配房间

来源:互联网 发布:闸机 软件 编辑:程序博客网 时间:2024/05/16 01:24

题目描述 Description
yh拥有一条街道,街道上共有n间房子,每间房子的坐标为xi(yh的房子比较神奇,可能重叠)。
同时,yh有m个女朋友(这是事实),yh打算给每位女朋友分配一间房子。两个女朋友间的距离相隔越近,她们之间产生冲突的可能就越高。yh想尽可能的减小女朋友间的冲突,于是他打算让他的女朋友间的最小距离最大,你能帮yh找出这个最大值吗?
输入描述 Input Description
第一行两个整数,n,m,表示yh有n间房子,有m个女朋友
第二行为n个整数,xi,表示各间房子的坐标。
输出描述 Output Description
输出1行,表示yh女朋友间的最小距离的最大值
样例输入 Sample Input
5 3
1 2 8 4 9
样例输出 Sample Output
3
数据范围及提示 Data Size & Hint
对于30%的数据,n<=100,m<=n,0<=xi<=10000;
对于100%的数据,n<=100000 ,m<=n,0 <= xi <= 1000000000

刚开始练习二分时做的,想我当时还稚嫩的加了那么多注释(╯▽╰)

//代码:#include <cstdio>#include <iostream>#include <cstring>#include <algorithm>using namespace std;int a[300000],n,m,x;bool cmp(int a,int b){    return a<b;}bool check(int x){    int last = 1;//先让第一个女朋友住第一间房     for(int i = 1; i < m; i ++)//要搜每两个女朋友之间的距离,所以要搜m-1种次     {        int now = last + 1;//从上一个女朋友的房间向后遍历         while(now <= n && a[now]-a[last] < x)//如果还没出界并且两者之间的距离小于给出的数         now ++;//继续扩大距离         if(now == n+1)        return false;//如果出界了,就是当前距离放不下这么多女朋友,就返回false        last = now;//搜下一对女朋友(当前后一个和以后第一个)     }     return true;//这个距离OK }int main(){    scanf("%d%d",&n,&m);    for(int i = 1; i <= n; i ++)    {        scanf("%d",&a[i]);    }    sort(a+1,a+n+1,cmp);    int l = 0,r = a[n],mid;    while(l <= r)    {        mid = (l+r)>>1;        if(check(mid))//如果mid的距离可以全部放下所有女朋友         {            l = mid+1;//那我就再找找还有没有更大的距离         }        else//如果放不下         r = mid-1;//缩短每个女朋友之间的距离     }    printf("%d\n",l-1);//可行的那个最小距离的最大值     return 0;}
2 0
原创粉丝点击