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;
}

posted @ 2018-01-17 21:37  Cyhlnj  阅读(122)  评论(0编辑  收藏  举报