題目鏈接:點擊查看
題目大意:給出一個長度爲 n 的序列,每個數字的範圍是 [ 1 , C ] ,現在需要求一個子串,使得字串中的字母,要麼出現 0 次,要麼出現至少 K 次,問這個子串的最大長度是多少
題目分析:第一反應是二分+尺取,但感覺會超時,正解是線段樹,枚舉 1 ~ n 作爲子串的右端點,然後貪心找符合條件的左端點
對於任意一個位置 i ,再對於任意一個數字 b 來說,設 pos1 是數字 b 從位置 i 向左開始第一次出現的位置,pos2 是第 k 次出現的位置,pos3 是第 k - 1 次出現的位置(下面會用到),則對於數字 b 來說,可以選擇的左端點的區間範圍是 [ 1 , pos2 ] 和 [ pos1 + 1 , i ]
這樣當我們枚舉位置 i 時,假設位置 i 的數字爲 num ,其前一次出現的位置爲 pre,則因爲第 i 個位置是 num,所以區間 [ pre + 1 , i ] 這段區間對左端點的貢獻集體減一,因爲如果還沒有第 i 個數字出現的話,那麼對於數字 num 來說,區間 [ pre + 1 , i - 1 ] 這段區間對左端點的貢獻都爲 1 ,所以當加入第 i 個位置的 num 後,需要羣體減一
同時,因爲新加入了一個 num 的位置,所以原先 [ 1 , pos2 ] 的這段區間擴大到了 [ 1 , pos3 ] 這麼大,相當於 [ pos2 + 1 , pos3 ] 這段區間對左端點的貢獻集體加一了
因爲對於貢獻來說,既有羣體加一,又有羣體減一,所以當一個節點的相對貢獻大於等於 0 時,說明當前節點可以選做爲左端點,每次處理完後,貪心去尋找相對貢獻大於等於 0 的最左端的位置,然後更新答案即可
代碼:
#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<cassert>
using namespace std;
typedef long long LL;
typedef unsigned long long ull;
const int inf=0x3f3f3f3f;
const int N=1e5+100;
vector<int>pos[N];
struct Node
{
int l,r,mmax,lazy;
}tree[N<<2];
void pushup(int k)
{
tree[k].mmax=max(tree[k<<1].mmax,tree[k<<1|1].mmax);
}
void pushdown(int k)
{
if(tree[k].lazy)
{
int lz=tree[k].lazy;
tree[k].lazy=0;
tree[k<<1].lazy+=lz;
tree[k<<1].mmax+=lz;
tree[k<<1|1].lazy+=lz;
tree[k<<1|1].mmax+=lz;
}
}
void build(int k,int l,int r)
{
tree[k].l=l;
tree[k].r=r;
tree[k].mmax=tree[k].lazy=0;
if(l==r)
return;
int mid=l+r>>1;
build(k<<1,l,mid);
build(k<<1|1,mid+1,r);
}
void update(int k,int l,int r,int val)
{
if(tree[k].r<l||tree[k].l>r)
return;
if(tree[k].l>=l&&tree[k].r<=r)
{
tree[k].lazy+=val;
tree[k].mmax+=val;
return;
}
pushdown(k);
update(k<<1,l,r,val);
update(k<<1|1,l,r,val);
pushup(k);
}
int query(int k)
{
if(tree[k].mmax<0)
return inf;
if(tree[k].l==tree[k].r)
return tree[k].l;
pushdown(k);
if(tree[k<<1].mmax>=0)
return query(k<<1);
else
return query(k<<1|1);
}
void init(int c)
{
for(int i=1;i<=c;i++)
{
pos[i].clear();
pos[i].push_back(0);
}
}
int main()
{
#ifndef ONLINE_JUDGE
// freopen("data.in.txt","r",stdin);
// freopen("data.out.txt","w",stdout);
#endif
// ios::sync_with_stdio(false);
int n,c,k;
while(scanf("%d%d%d",&n,&c,&k)!=EOF)
{
init(c);
build(1,1,n);
int ans=0;
for(int i=1;i<=n;i++)
{
int num;
scanf("%d",&num);
update(1,pos[num].back()+1,i,-1);
if(pos[num].size()>k)
update(1,1,pos[num][pos[num].size()-k],-1);
pos[num].push_back(i);
if(pos[num].size()>k)
update(1,1,pos[num][pos[num].size()-k],1);
ans=max(ans,i-query(1)+1);
}
printf("%d\n",ans);
}
return 0;
}