您的位置:首页 > 其它

poj 3320 Jessica's Reading Problem(尺取)

2016-09-22 13:02 309 查看
Jessica's Reading Problem

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 10852 Accepted: 3637
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

Source
POJ Monthly--2007.08.05, Jerry

注意头在往后移的时候,若头在这一段出现一次,可以删除,但是如果出现多次,不能删除,所以用map记录比较好。

代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<map>
#include<set>
using namespace std;
const int maxn = 1e6+5;
int a[maxn];
int main(void)
{
int n;
while(cin >> n)
{
set<int> s1;
map<int, int> m;
for(int i = 0; i < n; i++) scanf("%d", &a[i]), s1.insert(a[i]);
int ans = n, s = 0, e = 0, S = s1.size();
while(1)
{
while(e < n && m.size() < S)
m[a[e++]]++;
if(m.size() < S) break;
ans = min(ans, e-s);
m[a[s]] == 1 ? m.erase(a[s]) : m[a[s]]--;
s++;
}
printf("%d\n", ans);
}
return 0;
}
/*
13
1 2 2 3 4 1 2 3 4 2 3 2 1
输出:4
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 尺取