背景:
清明节放假前的坑(那天上午有比赛,效率很低)。
题目传送门:
https://www.luogu.org/problemnew/show/P3069
题意:
有
n
n
n头奶牛,每一头奶牛都有颜色,现在要可以赶走
m
m
m头奶牛,求颜色相同的最长的连续的奶牛的数量。
思路:
显然对于一个区间,若里面有不超过
(
m
+
1
)
(m+1)
(m+1)种颜色,那么它一定合法(可以删除元素使得颜色一样)。
维护一个单调队列使得颜色数不超过
(
m
+
1
)
(m+1)
(m+1)即可。
那就
O
K
OK
OK了。
代码:
#include<cstdio>
#include<cstring>
#include<map>
#include<algorithm>
using namespace std;
map<int,int> MAP;
int n,m,ans=0;
int a[100010],tot[100010];
int main()
{
int tmp=0;
scanf("%d %d",&n,&m);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
if(!MAP[a[i]]) MAP[a[i]]=++tmp;
}
int head=1,tail=0,cnt=0;
while(tail<n)
{
tail++;
if(!tot[MAP[a[tail]]]) cnt++;
tot[MAP[a[tail]]]++;
while(head<=tail&&cnt>m+1)
{
tot[MAP[a[head]]]--;
if(!tot[MAP[a[head]]]) cnt--;
head++;
}
if(cnt<=m+1) ans=max(ans,tot[MAP[a[tail]]]);
}
printf("%d",ans);
}