3048: [Usaco2013 Jan]Cow Lineup
Time Limit: 2 Sec Memory Limit: 128 MBSubmit: 189 Solved: 139
[Submit][Status][Discuss]
Description
Farmer John's N cows (1 <= N <= 100,000) are lined up in a row. Each cow is identified by an integer "breed ID" in the range 0...1,000,000,000; the breed ID of the ith cow in the lineup is B(i). Multiple cows can share the same breed ID. FJ thinks that his line of cows will look much more impressive if there is a large contiguous block of cows that all have the same breed ID. In order to create such a block, FJ chooses up to K breed IDs and removes from his lineup all the cows having those IDs. Please help FJ figure out the length of the largest consecutive block of cows with the same breed ID that he can create by doing this.
Input
* Line 1: Two space-separated integers: N and K.
* Lines 2..1+N: Line i+1 contains the breed ID B(i).
Output
* Line 1: The largest size of a contiguous block of cows with identical breed IDs that FJ can create.
Sample Input
2
7
3
7
7
3
7
5
7
INPUT DETAILS: There are 9 cows in the lineup, with breed IDs 2, 7, 3, 7, 7, 3, 7, 5, 7. FJ would like to remove up to 1 breed ID from this lineup.
Sample Output
OUTPUT DETAILS: By removing all cows with breed ID 3, the lineup reduces to 2, 7, 7, 7, 7, 5, 7. In this new lineup, there is a contiguous block of 4 cows with the same breed ID (7).
HINT
单调队列,当队列中数字种数多于k+1时就要弹队头
#include<cmath>
#include<ctime>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<complex>
#include<iostream>
#include<algorithm>
#include<iomanip>
#include<vector>
#include<string>
#include<bitset>
#include<queue>
#include<map>
#include<set>
using namespace std;
inline int read()
{
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch<='9'&&ch>='0'){x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}
return x*f;
}
void print(int x)
{if(x>=10)print(x/10);putchar(x%10+'0');}
const int N=100100;
int a[N];
bool book[N];
map<int,int>mp;
int q[N];
int main()
{
int n=read(),K=read()+1;
register int i,ans=0,now=0,head=1,tail=1;
for(i=1;i<=n;++i)a[i]=read();//cout<<"DSF"<<endl;
for(i=1;i<=n;++i)
{
if(!mp[a[i]])now++;mp[a[i]]++;//cout<<now<<endl;
while(now>K&&head<tail){if(!(--mp[a[q[head++]]]))now--;}
ans=max(mp[a[i]],ans);q[tail++]=i;
}
print(ans);puts("");
return 0;
}
/*
9 1
2
7
3
7
7
3
7
5
7
4
*/