「杂题乱刷」洛谷 P1712

链接

下位蓝。

题目可以用尺取法 + 区间加的方式来做。

image

参考代码:

点击查看代码
/*
Tips:
你数组开小了吗?
你MLE了吗?
你觉得是贪心,是不是该想想dp?
一个小时没调出来,是不是该考虑换题?
*/
#include<bits/stdc++.h>
using namespace std;
#define map unordered_map
#define forl(i,a,b) for(register long long i=a;i<=b;i++)
#define forr(i,a,b) for(register long long i=a;i>=b;i--)
#define lc(x) x<<1
#define rc(x) x<<1|1
#define mid ((l+r)>>1)
#define cin(x) scanf("%lld",&x)
#define cout(x) printf("%lld",x)
#define lowbit(x) x&-x
#define pb push_back
#define pf push_front
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
#define endl '\n'
#define QwQ return 0;
#define ll long long
ll t;
ll n,m,tag[20000010],sum[20000010],b[2000010],k,ans=1e18,L=1;
struct node{
	ll l,r,len;
}a[500010];
bool cmp(node x,node y){
	return x.len<y.len;
}
void upd(ll x,ll l,ll r,ll ql,ll qr,ll y)
{
	if(r<ql || qr<l)
		return ;
	if(ql<=l && r<=qr)
	{
		tag[x]+=y,sum[x]+=y;
		return ;
	}
	upd(lc(x),l,mid,ql,qr,y),upd(rc(x),mid+1,r,ql,qr,y);
	sum[x]=max(sum[x*2],sum[x*2+1])+tag[x];
}
void solve()
{
	cin>>n>>m;
	forl(i,1,n)
		cin>>a[i].l>>a[i].r,a[i].len=a[i].r-a[i].l,b[++k]=a[i].l,b[++k]=a[i].r;
	sort(a+1,a+n+1,cmp),sort(b+1,b+k+1);
	k=unique(b+1,b+k+1)-b-1;
	forl(i,1,n)
		a[i].l=lower_bound(b+1,b+k+1,a[i].l)-b,a[i].r=lower_bound(b+1,b+k+1,a[i].r)-b;
	forl(i,1,n)
	{
		upd(1,1,n*2,a[i].l,a[i].r,1);
		while(sum[1]>=m)
			upd(1,1,n*2,a[L].l,a[L].r,-1),ans=min(ans,a[i].len-a[L].len),L++;
	}
	if(ans==1e18)
		cout<<-1<<endl;
	else
		cout<<ans<<endl;
}
int main()
{
	IOS;
	t=1;
	//cin>>t;
	while(t--)
		solve();
    /******************/
	/*while(L<q[i].l) */
	/*    del(a[L++]);*/
	/*while(L>q[i].l) */
	/*    add(a[--L]);*/
	/*while(R<q[i].r) */
	/*	  add(a[++R]);*/
	/*while(R>q[i].r) */
	/*    del(a[R--]);*/
    /******************/
	QwQ;
}
posted @ 2024-02-17 19:28  wangmarui  阅读(4)  评论(0编辑  收藏  举报