codevs 3037 线段覆盖5 (dp+二分+快排)

题目描述 Description
数轴上有n条线段,线段的两端都是整数坐标,坐标范围在0~10^18,每条线段有一个价值,请从n条线段中挑出若干条线段,使得这些线段两两不覆盖(端点可以重合)且线段价值之和最大。

输入描述 Input Description
第一行一个整数n,表示有多少条线段。

接下来n行每行三个整数, ai bi ci,分别代表第i条线段的左端点ai,右端点bi(保证左端点<右端点)和价值ci。

输出描述 Output Description
输出能够获得的最大价值

样例输入 Sample Input
3

1 2 1

2 3 2

1 3 4

样例输出 Sample Output
4

数据范围及提示 Data Size & Hint
n <= 1000000

0<=ai,bi<=10^18

0<=ci<=10^9

数据输出建议使用long long类型(Pascal为int64或者qword类型)

思路:和线段覆盖4思路一致,改下数据范围即可

代码如下

#include <iostream>  
#include <cstdio>  
#include <cstring>  
#include <cmath>  
#include <algorithm>
#define LL long long int 
using namespace std;  
const int N=1000005;
struct line
{
    LL l,r,w;//分别表示左右端点的坐标和该线段的价值。
}a[N];
LL dp[N],p[N];
bool cmp(line a,line b)
{
    return a.r<b.r;
}
inline int check(LL l,LL r,LL left)
{
    while(r-l>1)
    {
        int mid=(r+l)/2;
        if(a[mid].r>left)
        {
            r=mid;
        }
        else 
        l=mid;
    }
    return l;
}
int main()
{
        int n;
        scanf("%d",&n);

        for(int i=1;i<=n;i++)
        {
            scanf("%lld%lld%lld",&a[i].l,&a[i].r,&a[i].w);
        }
        sort(a+1,a+1+n,cmp);

        dp[0]=0;
        p[0]=0;
        for(int i=1;i<=n;i++)
        {

            dp[i]=p[check(0,i,a[i].l)]+a[i].w;
            p[i]=max(dp[i],p[i-1]);
        }
        printf("%lld\n",p[n]);
    return 0;
}

读入优化

#include <iostream>  
#include <cstdio>  
#include <cstring>  
#include <cmath>  
#include <algorithm>
#define LL long long int 
using namespace std;  
const int N=1000001;
struct line
{
    LL l,r,w;//分别表示左右端点的坐标和该线段的价值。
}a[N];
LL dp[N],p[N];
LL read()
{
    LL x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
bool cmp(line a,line b)
{
    return a.r<b.r;
}
inline int check(LL l,LL r,LL left)
{
    while(r-l>1)
    {
        int mid=(r+l)/2;
        if(a[mid].r>left)
        {
            r=mid;
        }
        else 
        l=mid;
    }
    return l;
}
int main()
{
        int n;
        //scanf("%d",&n);
        n=read();
        for(int i=1;i<=n;i++)
        {
            //scanf("%lld%lld%lld",&a[i].l,&a[i].r,&a[i].w);
            a[i].l=read();
            a[i].r=read();
            a[i].w=read();
        }
        sort(a+1,a+1+n,cmp);

        dp[0]=0;
        p[0]=0;
        for(int i=1;i<=n;i++)
        {

            dp[i]=p[check(0,i,a[i].l)]+a[i].w;
            p[i]=max(dp[i],p[i-1]);
        }
        printf("%lld\n",p[n]);
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值