UVA 1616 Caravan Robbers 【二分+贪心+枚举分母】

题目链接

题意

给n个互不相包含的区间,求出一个长度的最大值,使得可以在每个区间中选出这样一个长度的子区间,这些子区间互不相交。结果用分数表示

分析

先考虑如果给定了区间长度能不能选出这样的区间。因为题中说了区间互不包含,所以可以直接把所有区间先按左端点排序再按右端点排序,每个区间都尽量取靠近左端点的子区间。(如果没有说区间不相互包含的话,就要维护优先队列)
然后用二分可以求出这个最大长度。这个题卡精度,精度要到1e-9才能过,所以对浮点数二分时候最好直接规定二分次数,不要设EXP,就可以规避卡精度的问题。

最后是用分数表示结果。最开始想的是直接在二分的时候就直接对分母进行二分,但这样显然是不正确的,也得不到正确结果。对用分数表示结果的问题一般直接枚举分母,因为原区间的长度都是整数,最极端的情况就是1/区间数量,所以从1到n枚举分母,然后乘以二分出来的结果算出分子。同样这里要处理精度问题(算出来的分数化成小数再与二分出来的结果进行比较),结果就是误差最小的分数。

(疑问:为什么算分子是要四舍五入或者用天花板函数?p=round(mid*q) p=celi(mid*q)

AC代码

//UVA 1616 Caravan Robbers
//AC 2016-8-1 09:31:14
//Greedy, Binary Search, Enumeration
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cctype>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <set>
#include <string>
#include <map>
#include <queue>
#include <deque>
#include <list>
#include <sstream>
#include <stack>
using namespace std;

#define cls(x) memset(x,0,sizeof x)
#define inf(x) memset(x,0x3f,sizeof x)
#define neg(x) memset(x,-1,sizeof x)
#define ninf(x) memset(x,0xc0,sizeof x)
#define st0(x) memset(x,false,sizeof x)
#define st1(x) memset(x,true,sizeof x)
#define INF 0x3f3f3f3f
#define lowbit(x) x&(-x)
#define bug cout<<"here"<<endl;
//#define debug

int n;

int gcd(int a,int b)
{
    if(b==0)
        return a;
    return gcd(b,a%b);
}

struct interval
{
    long double l,r;
    bool operator< (const interval &rhs) const
    {
        if(l==rhs.l)
            return r<rhs.r;
        return l<rhs.l;
    }
}inters[100010];

bool valid(long double x)
{
    long double cur=0;
    for(int i=0;i<n;++i)
    {
        cur=max(cur,inters[i].l);
        cur+=x;
        if(cur>inters[i].r)
            return false;
    }
    return true;
}

int main()
{
    #ifdef debug
        freopen("E:\\Documents\\code\\input.txt","r",stdin);
        freopen("E:\\Documents\\code\\output.txt","w",stdout);
    #endif
    while(cin>>n)
    {
        for(int i=0;i<n;++i)
            cin>>inters[i].l>>inters[i].r;
        sort(inters,inters+n);
        long double a=0,b=1000010,mid;
        for(int i=0;i<100;++i)
        {
            mid=(a+b)/2;
            if(valid(mid))a=mid;
            else b=mid;
        }
        int p,q=1,fp=100100,fq=1;
        for(q=1;q<=n;++q)
        {
            p=round(mid*q);
            if(fabs((long double)p/q-mid)<fabs((long double)fp/fq-mid))
            {
                fp=p;
                fq=q;
            }
        }
        int g=gcd(max(fp,fq),min(fp,fq));
        cout<<fp/g<<"/"<<fq/g<<endl;
    }
    return 0;
}

转载于:https://www.cnblogs.com/DrCarlluo/p/6580602.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值