POJ 3320 Jessica's Reading Problem

来源:互联网 发布:批判性思维工具 知乎 编辑:程序博客网 时间:2024/05/19 20:42

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


Jessica's Reading Problem

Time Limit: 1000MS
Memory Limit: 65536KTotal Submissions: 10206
Accepted: 3395

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

思路:map的应用。用map记录一个数出现的次数,并且记录最后一个数初始出现的位置。这样答案初始就为该位置减去首位置加上1,此时还要更新当前区间的计数,将多余的计数还回去。然后从这个位置开始,每次将右边位置向右移动一下,接着不断右移左边位置,什么时候能移动呢?当最左边的数的计数大于1时移动,因为区间内还有该值,当前的值要不要无所谓,所以我们当然不要它。当最左边不能再右移了,就更新答案。详见代码。

附上AC代码:
#include <cstdio>#include <map>#include <algorithm>//#pragma comment(linker, "/STACK:102400000, 102400000")using namespace std;const int maxn = 1000005;int num[maxn];map<int, int> cnt;int n;int main(){#ifdef LOCALfreopen("input.txt", "r", stdin);freopen("output.txt", "w", stdout);#endifwhile (~scanf("%d", &n)){for (int i=0; i<n; ++i)scanf("%d", num+i);int l=0, r=0;cnt.clear();for (int i=0; i<n; ++i){if (cnt[num[i]] == 0)r = i;++cnt[num[i]];}for (int i=r; i<n; ++i)--cnt[num[i]];int ans = r-l+1;--r;while (++r < n){++cnt[num[r]];while (cnt[num[l]] > 1)--cnt[num[l]], ++l;ans = min(ans, r-l+1);}printf("%d\n", ans);}return 0;}


1 0
原创粉丝点击