本文主要是介绍poj 3320 A - Jessica's Reading Problem,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
前几天才了解的一个小技巧取尺法,然后就找了一部分题练习一下,这里我按自己的理解总结一下取尺法(如果有错误或者蹩脚的地方欢迎找茬)
取尺法主要解决在一串数或字符中求能满足一定条件的最短的长度,首先从串头开始找到第一个满足所给条件的子串,然后让左端点逐渐向右移动,在搜索的过程中能找到所有满足条件的情况并找到最小值就可以了,注意要正确找到循环跳出的条件
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
经典的取尺法:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <map>
using namespace std;
int a[1000005];
map<int,int> p;
int main()
{
int x;
while(cin>>x)
{
int sum=0;
p.clear();
for(int i=0; i<x; i++)
{
scanf("%d",&a[i]);
if(p[a[i]]==0)
sum++;
p[a[i]]=1;
}
int l=0,r=0,min=x+1,sum1=0;
p.clear();
while(1)
{
while(r<x&&sum1<sum)
{
if(p[a[r]]==0)
sum1++;
p[a[r]]++;
r++;
}
if(sum1<sum)
break;
if(r-l<min)
min=r-l;
if(p[a[l]]==1)
{
p[a[l]]=0;
sum1--;
}
else
p[a[l]]--;
l++;
}
printf("%d\n",min);
}
return 0;
}
这篇关于poj 3320 A - Jessica's Reading Problem的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!