[bzoj4653][离散化][线段树]区间

题目

http://www.lydsy.com/JudgeOnline/problem.php?id=4653

一句话题意(Orz WerKeyTom_FTD):

现在有 n个区间,选择一些区间使得其中能找出m个区间交集不为空。
最小化选择的最大区间长度减最小区间长度

分析

一开始想按端点排序
然后双指针维护几段连续的区间使合法(有一个点被覆盖m次)
给这几段区间按长度排序(Splay插入)
然后取这几段区间中的m个(长度连续,但位置不一定连续)
时间O(n^2logn)
其中双指针+splay插入O(nlogn),取m个时O(n)
大概60分吧(其实我已经很满意了QAQ)

然后看有人有二分答案的80分做法???

正解

按长度排序
端点离散化
线段树维护每个点最大覆盖区间数
双指针
如果最大覆盖区间数大于等于m则更新答案

这里再提醒一点
unique()返回的是无重复最后一个的下一个(左闭右开)
所以

top=unique(c+1,c+top+1)-c-1;

完整ac代码

#include<cstdio>
#include<algorithm>
#define lc (x<<1)
#define rc ((x<<1)^1)
#define mid ((l+r)>>1)
#define N 500010
#define INF 2147483647
using namespace std;
int t[N<<3],tag[N<<3],p,q,l,r,top,n,m,c[N<<1],ans;
struct Edge{
    int l,r;
}a[N];
bool cmp(Edge p,Edge q){
    return p.r-p.l<q.r-q.l;
}
void Mt(int x){
    t[x]=max(t[lc],t[rc])+tag[x];
}
void Upd(int x,int l,int r,int v){
    if(p<=l&&r<=q){
        t[x]+=v;
        tag[x]+=v;
        return ;
    }
    if(p<=mid)Upd(lc,l,mid,v);
    if(q>mid)Upd(rc,mid+1,r,v);
    Mt(x);
}
int main(){
    freopen("data.txt","r",stdin);
    ans=INF;
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++){
        scanf("%d%d",&a[i].l,&a[i].r);
        c[++top]=a[i].l;
        c[++top]=a[i].r;
    }
    sort(c+1,c+top+1);
    top=unique(c+1,c+top+1)-c-1;
    sort(a+1,a+n+1,cmp);
    for(int i=1;i<=n;i++){
        a[i].l=lower_bound(c+1,c+top+1,a[i].l)-c;
        a[i].r=lower_bound(c+1,c+top+1,a[i].r)-c;
    }
    for(l=1;l<=n;p=a[l].l,q=a[l].r,Upd(1,1,top,-1),l++){
        while(r<n&&t[1]<m){
            p=a[++r].l;
            q=a[r].r;
            Upd(1,1,top,1);
        }
        if(r==n&&t[1]<m)break;
        ans=min(ans,c[a[r].r]-c[a[r].l]-c[a[l].r]+c[a[l].l]);
    }
    if(ans==INF)printf("-1\n");
    else printf("%d\n",ans);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值