您的位置:首页 > 其它

POJ - 3320 Jessica's Reading Problem(尺取法)

2015-09-29 16:24 387 查看
Jessica's Reading Problem

Time Limit: 1000MS Memory Limit: 65536KB 64bit IO Format: %I64d & %I64u
Submit Status

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开始读一本书,书总共有P页,第i页有一个知识点ai,同一个知识点可能会出现多次,她希望读书中一段连续的页数来掌握所有的知识点,请求出需要读的最少的页数。
分析:我们用尺取法来求解。
(1).初始化s=t=num=0。 
(2).如果t小于P,且num小于n(所有知识点个数),就一直增加t,如果出现新的知识点,则num++。
(3).如果num小于n,退出。否则更新res。
(4).count[s]--,如果这个知识点不再有出现,则num--,s++。回到(2)。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<set>
#include<map>
#include<algorithm>
using namespace std;

const int MAXN = 1000000 + 1000;
int a[MAXN];
int p;

int main()
{
while (scanf("%d", &p) != EOF)
{
for (int i = 0; i < p; i++)
scanf("%d", &a[i]);

set<int>all;
for (int i = 0; i < p; i++)
all.insert(a[i]);
int n = all.size();

//利用尺取法来求解
int s = 0, t = 0, num = 0;
map<int, int>count;
int ret = p;
for (;;)
{
while (t < p && num < n)
{
if (count[a[t++]]++ == 0)
{
num++;
}
}
if (num < n) break;
ret = min(ret, t - s);
if (--count[a[s++]] == 0)
num--;
}
printf("%d\n", ret);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: