• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
dwtfukgv
博客园    首页    新随笔    联系   管理    订阅  订阅
UVa 1616 Caravan Robbers (二分+贪心)

题意:给定 n 个区间,然后把它们变成等长的,并且不相交,问最大长度。

析:首先是二分最大长度,这个地方精度卡的太厉害了,都卡到1e-9了,平时一般的1e-8就行,二分后判断是不是满足不相交,找出最长的。这个题并不难,

就是精度可能控制不好,再就是把小数化成分数时,可能有点麻烦。

代码如下:

#include <iostream>
#include <cmath>
#include <cstdlib>
#include <set>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;
const int INF = 0x3f3f3f3f;
const double eps = 1e-9;//注意精度
const int maxn = 1e5 + 5;
struct node{
    int l, r;
    bool operator < (const node &p) const{
        return r < p.r;
    }
};
node a[maxn];
int n;

int main(){
//    freopen("in.txt", "r", stdin);
    while(scanf("%d", &n) == 1){
        for(int i = 0; i < n; ++i)
            scanf("%d %d", &a[i].l, &a[i].r);

        double r = 1000000, l = 0, ans = 0;

        sort(a, a+n);
        while(r - l > eps){//二分
            double m = ((l+r)/2.0);
            bool ok = true;
            double s = 0;
            for(int i = 0; i < n; ++i){//贪心
                if(s < a[i].l)  s = a[i].l;
                if(s + m > a[i].r){ ok = false;   break;  }
                s += m;
            }
            if(ok){ ans = m;   l = m;  }
            else   r = m;
        }

        int rp = 0, rq = 1;//小数化分数
        for(int p, q = 1; q <= n; ++q){
            p = round(ans * q);
            if(fabs((double)p/q - ans) < fabs((double)rp/rq - ans)){
                rp = p;  rq = q;  
            }
        }

        printf("%d/%d\n", rp, rq);
    }
    return 0;
}

 

posted on 2016-07-05 23:43  dwtfukgv  阅读(1065)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3