Jessica‘s Reading Problem
Jessica’s a very lovely girl wooed by lots of boys. Recently she has a problem. The final exam is coming, yet she has spent little time on it. If she wants to pass it, she has to master all ideas included in a very thick text book. The author of that text book, like other authors, is extremely fussy about the ideas, thus some ideas are covered more than once. Jessica think if she managed to read each idea at least once, she can pass the exam. She decides to read only one contiguous part of the book which contains all ideas covered by the entire book. And of course, the sub-book should be as thin as possible.
A very hard-working boy had manually indexed for her each page of Jessica’s text-book with what idea each page is about and thus made a big progress for his courtship. Here you come in to save your skin: given the index, help Jessica decide which contiguous part she should read. For convenience, each idea has been coded with an ID, which is a non-negative integer.
Input
The first line of input is an integer P (1 ≤ P ≤ 1000000), which is the number of pages of Jessica’s text-book. The second line contains P non-negative integers describing what idea each page is about. The first integer is what the first page is about, the second integer is what the second page is about, and so on. You may assume all integers that appear can fit well in the signed 32-bit integer type.
Output
Output one line: the number of pages of the shortest contiguous part of the book which contains all ideals covered in the book.
Sample Input
5
1 8 8 8 1
Sample Output
2
大意:找最短子序列,覆盖原序列中所有不重合的元素
尺取法:右指针先走到符合条件的地方,左指针一步一步向右优化
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<cstdio>
#include<set>
#include<iostream>
#include<map>
#define ll long long
using namespace std;
ll a[1010100];
map<int,int>cnt; //学习map的应用 int 到 int
//ll cnt[1000000000]; 数组开不了
ll ans=1e18;
int main()
{
ll p;
//memset(cnt,0,sizeof(cnt));
scanf("%lld",&p);
set<int>S;
for(int i=1;i<=p;i++)
{
scanf("%lld",&a[i]);
S.insert(a[i]);
}
ll type=S.size(); //共有几种
//cout<<type<<endl;
ll l=1,r=1;
ll tmp_type=0;
while(1)
{
while(r<=p && tmp_type<type)
{
if(cnt[a[r++]]++ ==0)
tmp_type++;
//cout<<r<<endl;
//cout<<"tmp_type: "<<tmp_type<<endl;
}
if( tmp_type<type ) //tmp_type<type 不符合条件
break;
ans=min(ans,r-l);
if(--cnt[a[l++]] ==0) //左指针向右走是必然,tmp_type减不减则要看--cnt是不是等于0
{
tmp_type--;
}
//cout<<"l: "<<l<<"r: "<<r<<endl;
//cout<<tmp_type<<endl;
}
cout<<ans<<endl;
return 0;
}
/*
10
3 6 3 5 7 8 2 3 3 2
*/