POJ3320 Jessica's Reading Problem(双指针)

来源:互联网 发布:淘宝网投诉电话 编辑:程序博客网 时间:2024/06/09 21:13

题目链接:http://poj.org/problem?id=3320


Jessica's Reading Problem
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 7319 Accepted: 2303

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

51 8 8 8 1

Sample Output

2

题意:Jessica有一本书,每一页上都有一个知识点,现在她想要阅读连续的一些页把所有的知识点都看到,问她需要阅读的最少页数。


这道题很容易想到用双指针来做,首先从第一页开始阅读直到覆盖所有的知识点,然后去掉第一页的知识点,再找接下来能覆盖所有知识点的页数。重复这些步骤就可以找到最小的阅读页数。由于知识点数字可能较大,所以用map来判断知识点是否出现过。


#include <iostream>#include <cstdio>#include <cstring>#include <string>#include <map>#include <algorithm>using namespace std;#define inf 0x3f3f3f3fint n;int a[1000005],b[1000005];map<int,int> cnt;//判断知识点当前出现次数int main(){while (scanf("%d",&n)!=EOF){for (int i=0;i<n;i++){scanf("%d",&a[i]);b[i]=a[i];}int ans=n,ii=0,jj=0,num=0;sort(b,b+n);int nn=unique(b,b+n)-b;//计算知识点的个数while (1){while (jj<n&&num<nn){if (cnt[a[jj]]==0)++num;++cnt[a[jj]];++jj;}if (num<nn) break;//如果知识点没有找齐说明已经到最后了,可以退出。ans=min(ans,jj-ii);--cnt[a[ii]];if (cnt[a[ii]]==0) --num;++ii;}printf("%d\n",ans);}return 0;}


0 0
原创粉丝点击