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
题意:
一本书有p页 每一页都有一个知识点ai 存在不同两页上的知识点相同的情况
求最少读连续的多少页书 能把所有的知识点全部覆盖到
尺取法:
反复的推进区间的开头和结尾 来求满足条件的最小区间的方法被称为尺取法
尺取法的复杂度为O(n).
题解:
初始化 start end sum =0;
然后推进end 直到恰好满足条件退出 如果区间已经到了结尾 仍不满足 则退出
然后更新答案 ans = min(ans,end-start);
然后start推进一位,要处理这时对sum的影响
1 #include <iostream> 2 #include <algorithm> 3 #include <cstring> 4 #include <cstdio> 5 #include <vector> 6 #include <cstdlib> 7 #include <iomanip> 8 #include <cmath> 9 #include <ctime> 10 #include <map> 11 #include <set> 12 #include <queue> 13 using namespace std; 14 #define lowbit(x) (x&(-x)) 15 #define max(x,y) (x>y?x:y) 16 #define min(x,y) (x<y?x:y) 17 #define MAX 100000000000000000 18 #define MOD 1000000007 19 #define pi acos(-1.0) 20 #define ei exp(1) 21 #define PI 3.141592653589793238462 22 #define INF 0x3f3f3f3f3f 23 #define mem(a) (memset(a,0,sizeof(a))) 24 typedef long long ll; 25 ll gcd(ll a,ll b){ 26 return b?gcd(b,a%b):a; 27 } 28 const int N=1e6+10; 29 const int mod=1e9+7; 30 int a[N]; 31 int main() 32 { 33 int n; 34 while(~scanf("%d",&n)){ 35 map<int,int>mp; 36 int num=0; 37 for(int i=0;i<n;i++){ 38 scanf("%d",a+i); 39 if(!mp[a[i]]) num++; 40 mp[a[i]]++; 41 } 42 int st=0,t=0,sum=0,ans=n; 43 mp.clear(); 44 while(1){ 45 while(t<n&&sum<num){ 46 if(!mp[a[t++]]++) 47 sum++; 48 } 49 if(sum<num) break; 50 ans = min(ans,t-st); 51 if(--mp[a[st++]]==0) 52 sum--; 53 } 54 printf("%d ",ans); 55 } 56 return 0; 57 }