POJ 3320 Jessica's Reading Problem (STL)

来源:互联网 发布:优化整站 编辑:程序博客网 时间:2024/06/06 03:48

题目链接:POJ 3320


题面:

Jessica's Reading Problem
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 10125 Accepted: 3367

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 containsP 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

51 8 8 8 1

Sample Output

2

Source

POJ Monthly--2007.08.05, Jerry


题意:

        给定1个序列,问最少取多长的连续子序列可以包含全部元素。


解题:

       比较容易想到的做法是二分长度,随后从头开始检验每个位置,通过一位位移动,删一个加一个,检验,然而复杂度是O(n*log(n)*log(n)),TLE。

       正确的解法是通过前后两个指针,先找到一个合法解,后移前面的指针p1,至不能包含全部元素,计算此时的值,若优于当前最优值,则更新,随后后移p2,至包含全部元素,不断循环此过程,直至到序列结尾。复杂度为O(n*log(n))。这种通过两个指针移动的方式,还是很经典的,需要总结。


代码:

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <set>#include <map>using namespace std;int a[1000010];set <int> s;map <int,int> check;int main(){    int n,sz,p1=0,p2=0,ans,tmp;scanf("%d",&n);for(int i=0;i<n;i++){scanf("%d",&a[i]);s.insert(a[i]);}    sz=s.size();for(int i=0;i<n;i++){check[a[i]]++;if(check.size()==sz){p1=0;p2=i;ans=p2-p1+1;break;}}while(p2<n){       while(1)   {   check[a[p1]]--;   if(check[a[p1]]==0)   check.erase(a[p1]);   p1++;   if(check.size()==sz)   continue;   else   {   tmp=p2-p1+2;   if(tmp<ans)   ans=tmp;   break;   }   }   while(1)   {   check[a[++p2]]++;           if(check.size()==sz)   break;   }}printf("%d\n",ans);return 0;}




0 0
原创粉丝点击