所谓尺取法,也就是取一段连续的区间。。。。好吧 ,这就是概念
http://poj.org/problem?id=3320
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
题意:一本书有p页,每页有一个知识点,不同的页可能含有同一个知识点,她希望通过阅读其中一些连续的一些页把所有的知识点都覆盖到,求阅读的最少页数
连续的区间,可以联想到尺取法,类似于那个给定序列长度n和k求n的连续子序列和大于等于k的最小的连续区间的长度,这里也是一样,我们可以先求出共有多少个知识点,设开头点s,结尾点e,
每次读到一个知识点就加1,记录每个知识点出现的次数,将结尾点往后推移,当读到的知识点等于n之后,就将开头点往后移,如果发现某个知识点被消去了,就接着将开头点s往前移直到再次使得读到的知识点出现,用res
更新最小的区间长度(e-s),这里用set来求知识点的个数,用map进行知识点与出现次数的映射
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<set>
#include<map>
using namespace std;
int p;
int a[1001000];
int main()
{
while(scanf("%d",&p)!=EOF)
{
set<int>all;
for(int i=0;i<p;i++)
{
scanf("%d",&a[i]);
}
for(int i=0;i<p;i++)
{
all.insert(a[i]);
}
int n=all.size();//n为知识点总的个数
int s=0,e=0,sum=0;//sum为包含的知识点数
int res=p;//注意这里是p!!!!!!!,之前这里搞了个n弄得wrong了2次。。。,后来才发现,因为虽然只有n个知识点,但是他需要阅读的页数是可能比这个大的。。
map<int,int>cou;
for(;;)
{
while(e<p&&sum<n){
if(cou[a[e++]]++==0)//出现新的知识点
{
sum++;
}
}
if(sum<n) break;
res=min(res,e-s);
if(--cou[a[s++]]==0)
{
sum--;
}
}
printf("%d\n",res);
}
return 0;
}

浙公网安备 33010602011771号