Poj

来源:互联网 发布:python 画时间轴 分钟 编辑:程序博客网 时间:2024/06/05 12:34

Jessica’s Reading Problem

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 13915 Accepted: 4773

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

Source

POJ Monthly–2007.08.05, Jerry

题意:给你一个P,P个数,然后让你求能包含所有元素值的数列的最短长度。例如:样例就是前两个,1,8,就可以包含数列中的所有值了

分析: 如果不用尺取的话有点棘手,用的话又得考虑这个数有没有出现过,出现了几次,最好hash下,但是看了下范围hash直接放弃,这时就可利用stl里面的map来实现映射关系,我们可以用尺取的思想,当然我们得预处理下一共有多少个不同的元素(利用set,也可以vector),然后让右指针不断的向右移动然后往map添加元素,当元素的种数和预处理的一致的时候就更新下答案,然后,然后就是尺取的思想啦

参考代码:

#include <cstdio>#include <iostream>#include <map>#include <set>using namespace std;const int N = 1e6 + 10;inline int read(){    int x=0,f=1;char ch=getchar();    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}    return x*f;}map<int,int> m;set<int> s;int h[N],a[N];int main(){    int n;cin>>n;    for(int i = 1;i <= n;i++) a[i] = read(),s.insert(a[i]);    int len = s.size();    int ans = INF,l,r,t;    l = r = 1;    t = 0;    while(true){        while(t < len && r <= n)            if(m[a[r++]]++ == 0) t++;//t记录不同元素的个数        if(t < len) break;        ans = min(ans,r-l);        if(ans == len)break;        t -= (--m[a[l++]] == 0)?1:0;//这里处理好就行了    }    cout<<ans<<endl;    return 0;}
  • 如有错误或遗漏,请私聊下UP,thx
原创粉丝点击