题解 二分基础 POJ2456

题意:有N个牛舍排在一条线上,坐标分别为X,求把C个牛各放入一个牛舍时最大化的最近的两头牛之间的距离。

做法:用二分法,和贪心法。将距离分割,判断最小距离为d是能否满足条件,最终选取最大值。

代码:

<span style="font-family:Microsoft YaHei;font-size:24px;">#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int n,c,i,pos[100000];
bool two(int d)
{
        int last=0;
        for(int i=1;i<c;i++)
        {
            int crt=last+1;
            while(crt<n&&pos[crt]-pos[last]<d)
            {
                crt++;
            }
            if(crt==n)return false;
            last=crt;
        }
        return true;
}
int main()
{
        scanf("%d%d",&n,&c);
    for(i=0;i<n;i++)
        scanf("%d",&pos[i]);
    sort(pos,pos+n);
    int ub=pos[n-1]-pos[0],lb=0;
    while(ub-lb>1)
    {
        int mid=(ub+lb)/2;
        if(two(mid))lb=mid;
        else ub=mid;
    }
    printf("%d",lb);
    return 0;
}
</span>

错误:超时。原因:使用了 cin。 

总结:在面对大量数据输入输出时,尽量用printf。

posted on 2014-07-19 16:39  一锅土豆  阅读(101)  评论(0编辑  收藏  举报