题目描述
You are given two integers C,K and an array of N integers a1,a2,...,aN. It is guaranteed that the value of ai is between 1 to C.
We define that a continuous subsequence al,al+1,...,ar(l≤r) of array a is a good subarray if and only if the following condition is met:
It implies that if a number appears in the subarray, it will appear no less than K times.
You should find the longest good subarray and output its length. Or you should print 0 if you cannot find any.
输入
There are multiple test cases.
Each case starts with a line containing three positive integers N,C,K(N,C,K≤105).
The second line contains N integer a1,a2,...,aN(1≤ai≤C).
We guarantee that the sum of Ns, the sum of Cs and the sum of Ks in all test cases are all no larger than 5×105.
输出
For each test case, output one line containing an integer denoting the length of the longest good subarray.
样例输入
复制样例数据
7 4 2
2 1 4 1 4 3 2
样例输出
4
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const ll mod=1e9+7;
const int modp=998244353;
const int maxn=1e5+50;
const double eps=1e-6;
#define lowbit(x) x&(-x)
#define INF 0x3f3f3f3f
inline int read()
{
int x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9')
{
if(ch=='-')
f=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9')
{
x=x*10+ch-'0';
ch=getchar();
}
return x*f;
}
int dcmp(double x){
if(fabs(x)<eps)return 0;
return (x>0)?1:-1;
}
int gcd(int a,int b)
{
return b?gcd(b,a%b):a;
}
ll qmod(ll a,ll b)
{
ll ans=1;
while(b)
{
if(b&1)
{
ans=(ans*a)%mod;
}
b>>=1;
a=(a*a)%mod;
}
return ans;
}
int N,C,K,a[maxn];
int t[maxn<<2],laz[maxn<<2];//t数组记录当前位置满足的数,最后查询数为C的位置即可
//线段树,维护t数组
void pushdown(int rt,int l,int r){
if(laz[rt]==0){
return;
}
t[rt<<1]+=laz[rt];
laz[rt<<1]+=laz[rt];
t[rt<<1|1]+=laz[rt];
laz[rt<<1|1]+=laz[rt];
laz[rt]=0;
}
void update(int rt,int l,int r,int a,int b,int c){
if(a<=l&&r<=b){
t[rt]+=c;
laz[rt]+=c;
return;
}
pushdown(rt,l,r);
int mid=(l+r)>>1;
if(b<=mid){
update(rt<<1,l,mid,a,b,c);
}
else if(a>mid){
update(rt<<1|1,mid+1,r,a,b,c);
}
else{
update(rt<<1,l,mid,a,b,c);
update(rt<<1|1,mid+1,r,a,b,c);
}
t[rt]=max(t[rt<<1],t[rt<<1|1]);
}
int aask(int rt,int l,int r){
if(l==r){
return l;
}
pushdown(rt,l,r);
int mid=(l+r)>>1;
if(t[rt<<1]==C){
return aask(rt<<1,l,mid);
}
else if(t[rt<<1|1]==C){
return aask(rt<<1|1,mid+1,r);
}
else{
return -1;
}
}
int main()
{
while(~scanf("%d %d %d",&N,&C,&K)){
vector<int> pos[maxn];
for(int i=1;i<=C;i++){
pos[i].push_back(0);
}
for(int i=1;i<=N;i++){
scanf("%d",&a[i]);
pos[a[i]].push_back(i);
}
if(K==1){
printf("%d\n",N);
continue;
}
memset(t,0,sizeof(t));
memset(laz,0,sizeof(laz));
int ans=0;
int cur[maxn]={0};//记录x出现了几次
for(int i=1;i<=N;i++){
int x=a[i];
int p=++cur[x];
update(1,1,N,i,i,C-1);//单点更新当前点
if(pos[x][p-1]+1<=pos[x][p]-1){
update(1,1,N,pos[x][p-1]+1,pos[x][p]-1,-1);//区间更新两个点之间
}
if(p>=K){
update(1,1,N,pos[x][p-K]+1,pos[x][p-K+1],1);//更新原本不可以的部分
}
int tmp=aask(1,1,N);
if(tmp!=-1){
ans=max(ans,i-tmp+1);
}
}
printf("%d\n",ans);
}
return 0;
}