1. 程式人生 > >Codeforces 813E Army Creation 主席樹(線上,求[l,r]內比x大的數的個數)

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