poj 3320 Jessica's Reading Problem(尺取法)

Description

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
解题思路:题意就是找出连续的最少页数包含所有知识点ID,典型的尺取法。用set统计知识点的总个数,然后尺取取出某个区间中含有所有知识点,如果有多个满足条件,则取最小的区间长度;注意:右指针向右移动,对应指向的知识点个数加1,如果出现新的知识点,对应种类数加1;左指针向右移动,对应知识点个数先减1,如果其个数减为0,则对应种类数减1。时间复杂度为O(PlogP)。
AC代码(407ms):
 1 #include<cstdio>
 2 #include<iostream>
 3 #include<algorithm>
 4 #include<string.h>
 5 #include<set>
 6 #include<map>
 7 using namespace std;
 8 const int maxn=1000005;
 9 int P,cnt,bg,ed,res,num,a[maxn];set<int> st;map<int,int> mp;
10 int main(){
11     while(~scanf("%d",&P)){
12         st.clear();mp.clear();//清空
13         for(int i=0;i<P;++i)scanf("%d",&a[i]),st.insert(a[i]);
14         cnt=st.size();bg=ed=num=0;res=P;//res初始化为P,表示最多读P页
15         while(1){
16             while(ed<P&&num<cnt){
17                 if(mp[a[ed++]]++==0)num++;//出现新的知识点
18             }
19             if(num<cnt)break;//如果尺取得到的区间中知识点个数小于总个数,不用继续循环了,直接退出
20             res=min(res,ed-bg);
21             if(--mp[a[bg++]]==0)num--;//队首元素的次数如果减为0,则种数num减1
22         }
23         printf("%d\n",res);
24     }
25     return 0;
26 }

 

posted @ 2018-08-25 20:24  霜雪千年  阅读(142)  评论(0编辑  收藏  举报