Jessica’s Reading Problem POJ - 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
解题:
有n个数。求一个最短的区间,这n个数都在这个区间出现过。
使用其他做法容易超时。
这里使用尺取法
原理:就像尺取虫一样,求解,
《挑战程序设计竞赛》提出尺取法是建立在这样的一个模型上:
找连续区间的问题,如果对于左端点s,第一个满足条件的右端点是t,那么对于左端点s+1,第一个满足条件的右端点是t’>=t
那么求所有的满足条件的区间就可以像尺取虫爬行的方式求解。
一只虫子慢慢蛄蛹
基本思路:
读入数据,利用set集合的特性,能够得出共有几处不同
总体来说,就还是尺取法,固定左边,移动右边,
再左边++,向右侧移动
右侧在原有的基础上移动,就行
但是在过程中需要利用map统计添加了的次数,这样左边++的时候,就能分清楚去掉左端点时的代价,
#include<iostream>
#include<algorithm>
#include<set>
#include<map>
using namespace std;
int a[1000010];
set<int> oo;
map<int,int> hh;
//给你一个n,下面有n个数。求一个最短的区间,这n个数都在这个区间出现过。
int main(){
int n;scanf("%d",&n);//cin>>n;
for(int i=1;i<=n;i++) {
scanf("%d",&a[i]);
oo.insert(a[i]);
}
int sumg=oo.size();
//set<int> s;
int ans=n;
int r=1,l=1;
int count=0;
while(1){
while(r<=n && count<sumg){
if(hh[a[r]]==0) count++;
hh[a[r++]]+=1;//次数+1
}
if(count<sumg) break;//没满,右边超过了
ans=min(ans,r-l);//应该要加1吧,,包含最后的那个
hh[a[l]]--;//次数--
if(hh[a[l++]]==0) count--;
}
printf("%d\n",ans);
return 0;
}