POJ3320 Jessica's Reading Problem(尺取法)

题目链接

Jessica's Reading Problem

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 17034   Accepted: 5898

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

以下参考自《挑战程序设计竞赛(第二版)》

我们假设从某一页s开始阅读,为了覆盖所有的知识点需要阅读到t。这样的话可以知道如果从s+1开始阅读的话,那么必须阅读到t'>=t页为止。由此这题也可以使用尺取法。

根据“set容器中只能存储键,是单纯的键的集合,其中键是不能重复的”这一性质可求出知识点的种类数。

用map维护知识点->出现次数的映射,利用下标操作添加元素或查找元素。

戳此参考 C++ STL map 下标操作注意事项

AC代码:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<sstream>
#include<vector>
#include<set>
#include<map>
using namespace std;
int P,a[1000010];
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	cin>>P;
	set<int> all;
	for(int i=1;i<=P;i++) 
	{
		cin>>a[i];
		all.insert(a[i]);
	}
	int n=all.size();//知识点的种类数 
	
	int s=1,t=1,num=0,res=P;
	map<int,int> count;//知识点->出现次数的映射 
	for(;;)
	{
		while(t<=P&&num<n)
		{
			if(count[a[t++]]++==0) num++;//出现新的知识点 
		}
		if(num<n) break;
		res=min(res,t-s);
		if(--count[a[s++]]==0) num--; 
	}
	
	cout<<res;
}

小细节:需要注意的是a数组应该设为全局变量,用cin输入数据记得关同步。

猜你喜欢

转载自blog.csdn.net/qq_40889820/article/details/82461810