題目連結:http://poj.org/problem?id=3320
Jessica's Reading Problem
Time Limit: 1000MS | Memory Limit: 65536K |
Total 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
5
1 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 0x3f3f3f3f
int 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;
}