POJ 3320 Jessica's Reading Problem(尺取法)

题目描述:
Jessica’s Reading Problem
Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u

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
题目大意:
找到最小的连续的页数使得这些页包含所有知识点

题目分析:
首先要明确的就是总共的知识点数,不管用什么方法,我是用的set(不包含重复元素的集合),set的大小就是知识点的个数
接下来就是要找包含全部知识点的全部页数,然后找最小值,对一个数组,定义两个指针,然后一个指针定在开头,另外一个指针从前往后扫,直到涵盖了全部知识点,这时候这个指针停止往前扫,末尾的指针往前去,如果还能涵盖全部知识点,那么末尾的指针继续往前,如果知识点变少了,那么前面的指针就要接着往前扫了,直到再次涵盖全部知识点,每次包含全部知识点时,要用打擂台的方法记录当前的最小值

代码:

#include "cstdio"
#include "map"
#include "set"
using namespace std;
int know[1000000+5];
int main()
{
    int i,p;
    set<int> all;
    while(scanf("%d",&p)!=EOF)
    {       
        for(i=0;i<p;i++)
        {
            scanf("%d",&know[i]);
            all.insert(know[i]);
        }
        int n=all.size(),s,res=p,cnt=0;
        map<int,int> count;
        i=s=0;
        while(1)
        {
            while(cnt<n&&i<p)
            {
                if(count[know[i++]]++==0) cnt++;
            }
            //最后一次往前扫,还没涵盖全部知识点就到了最后一页,退出
            if(cnt<n) break;
            if(res>i-s) res=i-s;
            if(--count[know[s++]]==0) cnt--;
        }
        printf("%d\n",res);
    }
    return 0;
}

你可能感兴趣的:(poj,尺取法)