Bzoj4653: [Noi2016]区间

题目

传送门

Sol

把区间按长度升序排序,双端点+离散化+线段树区间最大值

线段树标记永久化美滋滋

# include <bits/stdc++.h>
# define RG register
# define IL inline
# define Fill(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long ll;
const int _(5e5 + 1);

IL ll Read(){
    RG ll x = 0, z = 1; RG char c = getchar();
    for(; c < '0' || c > '9'; c = getchar()) z = c == '-' ? -1 : 1;
    for(; c >= '0' && c <= '9'; c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
    return x * z;
}

int n, m, ql[_], qr[_], id[_], o[_ << 1], cnt, ans = 2e9, idl[_], idr[_], val[_];
int mx[_ << 3], tag[_ << 3];

IL bool Cmp(RG int x, RG int y){  return qr[x] - ql[x] < qr[y] - ql[y];  }

IL void Modify(RG int x, RG int l, RG int r, RG int L, RG int R, RG int d){
    if(L <= l && R >= r){  mx[x] += d; tag[x] += d; return;  }
    RG int mid = (l + r) >> 1;
    if(L <= mid) Modify(x << 1, l, mid, L, R, d);
    if(R > mid) Modify(x << 1 | 1, mid + 1, r, L, R, d);
    mx[x] = max(mx[x << 1], mx[x << 1 | 1]) + tag[x];
}

int main(RG int argc, RG char* argv[]){
    n = Read(); m = Read();
    for(RG int i = 1; i <= n; ++i){
        ql[i] = Read(); qr[i] = Read(); id[i] = i;
        o[++cnt] = ql[i]; o[++cnt] = qr[i];
    }
    sort(o + 1, o + cnt + 1); sort(id + 1, id + n + 1, Cmp);
    cnt = unique(o + 1, o + cnt + 1) - o - 1;
    for(RG int i = 1; i <= n; ++i){
        val[i] = qr[id[i]] - ql[id[i]] + 1;
        idl[i] = lower_bound(o + 1, o + cnt + 1, ql[id[i]]) - o;
        idr[i] = lower_bound(o + 1, o + cnt + 1, qr[id[i]]) - o;
    }
    for(RG int i = 1, j = 0; i <= n; ++i){
        while(j < n && mx[1] < m) ++j, Modify(1, 1, cnt, idl[j], idr[j], 1);
        if(mx[1] < m) break;
        ans = min(ans, val[j] - val[i]);
        Modify(1, 1, cnt, idl[i], idr[i], -1);
    }
    printf("%d\n", ans == 2e9 ? -1 : ans);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值