Codeforces 813E Army Creation 主席树(在线,求[l,r]内比x大的数的个数)

点击打开链接

题意:n个数a[i],q次询问,n,a[i],q<=1e5.
每次问[l,r]内最多可以选多少个数,满足同一个数的出现次数不超过k?


设b[i] 从i开始数k个和a[i]相同的数的位置,不存在设为n+1;
则[l,r] 只要b[i]>r的数都能可以被选上,转化为求区间[l,r]内有多少个数>=r
题目要求在线 所以套用主席树 
建立权值线段树,前缀i内,第[l,r]大的数有多少个,ans=前缀r内[r,inf]个数-前缀i-1内[r,inf]个数 

#include <bits/stdc++.h>
using namespace std;
const int N=2e5+20;
int n,q,k,a[N],b[N];
vector<int> pos[N];//
struct node{
	int l,r,sum;
	//前缀i内第[l,r]大的数有多少个 
}T[N*40];
int cnt,root[N];
int build(int l,int r)
{
	int rt=++cnt;
	T[rt].sum=0,T[rt].l=T[rt].r=0;
	if(l==r)	return rt;
	int m=(l+r)>>1;
	T[rt].l=build(l,m);
	T[rt].r=build(m+1,r);
	return rt; 
}
void update(int l,int r,int &x,int y,int v,int pos)
{
	T[++cnt]=T[y],T[cnt].sum+=v;x=cnt;
	if(l==r)	return;
	int m=(l+r)>>1;
	if(pos<=m)
		update(l,m,T[x].l,T[y].l,v,pos);
	else
		update(m+1,r,T[x].r,T[y].r,v,pos);
}
void calc()
{
	for(int i=n;i>=1;i--)
	{
		int sz=pos[a[i]].size();
		if(sz<k)
			b[i]=n+1;
		else
			b[i]=pos[a[i]][sz-k];
		
		pos[a[i]].push_back(i);
	}
}
int query(int l,int r,int c,int L,int R=2e5)
{
	if(l>=L&&r<=R)	return T[c].sum;
	int m=(l+r)>>1;
	int ans=0;
	if(L<=m)
		ans+=query(l,m,T[c].l,L,R);
	if(R>m)
		ans+=query(m+1,r,T[c].r,L,R);
	return ans;
}
int main()
{
	while(cin>>n>>k)
	{
		for(int i=1;i<=n;i++)
			scanf("%d",&a[i]);
		calc();
		cnt=0;
		root[0]=build(1,n+1);
		for(int i=1;i<=n;i++)
			update(1,n+1,root[i],root[i-1],1,b[i]);//更新权值 
		int last=0,l,r;
		scanf("%d",&q);
		while(q--)
		{
			scanf("%d%d",&l,&r);
			l=((l+last)%n)+1;
			r=((r+last)%n)+1;
			if(l>r)
				swap(l,r);
			//[r+1,inf]查询前缀i内比r大的数有多少个 
			int ans=query(1,n+1,root[r],r+1,2e5)-query(1,n+1,root[l-1],r+1,2e5);
			printf("%d\n",ans);
			last=ans;
		}
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值