Educational Codeforces Round 22 E. Army Creation

时间:2022-11-19 13:31:14

Educational Codeforces Round 22 E. Army Creation


题意:求区间[L,R]内数字次数不超过k次的这些数字的数量的和

思路:和求区间内不同数字的数量类似,由于这里强制在线,主席树或者整体二分来做这道题,把pre[i]前驱改一下 变成前k个a[i]的位置

对于每个点,在root[i]这棵树中i处+1,pre[i]处-1,对于查询[L,R]就是查询root[R]中区间[L,R]的值

#include<bits/stdc++.h>
#define LL long long
#define P pair<int,int>
#define ls T[i].lc
#define rs T[i].rc
using namespace std;
const int N = 1e5 + 10;
int read(){
int x = 0;
char c = getchar();
while(c < '0' || c >'9') c = getchar();
while(c >= '0' && c <= '9') x = x * 10 + c - 48,c = getchar();
return x;
}
int n, k, q;
queue<int>qu[N];
int a[N];
struct node{
int lc,rc,cnt;
}T[N * 50];
int tot,root[N];
void update(int &i,int l,int r,int pos,int val){
T[++tot] = T[i];
i = tot;
T[i].cnt += val;
if(l >= r) return ;
int m = l + r >> 1;
if(pos <= m) update(ls,l,m,pos,val);
else update(rs,m+1,r,pos,val);
}
int query(int i,int pos,int l,int r){
if(r < pos) return 0;
if(l >= pos) return T[i].cnt;
int m = l + r >> 1;
int ans = 0;
if(pos <= m) ans += query(ls,pos,l,m);
return query(rs,pos,m+1,r) + ans;
}
int main()
{
n = read(),k = read();
tot = 0,root[0] = 0;
for(int i = 1;i <= n;i++){
a[i] = read();
root[i] = root[i-1];
update(root[i],1,n,i,1);
qu[a[i]].push(i);
if((int)qu[a[i]].size()>k){
int top = qu[a[i]].front();
update(root[i],1,n,top,-1);
qu[a[i]].pop();
}
}
q = read();
int l,r,last = 0;
while(q--){
l = (read() + last)%n + 1;
r = (read() + last)%n + 1;
if(l > r) swap(l,r);
printf("%d\n",last=query(root[r],l,1,n));
}
return 0;
}