Jessica's Reading Problem(尺取法)

Jessica's Reading Problem
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 6897   Accepted: 2144

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(1 ~ 1000000),后给出 P 个数,输出最小的长度序列,这个长度序列的数包含整个序列的所有不同的数。

 

       思路:

       尺取法。先统计数的种类 n,然后用两个变量分别指向开头和结尾(一开始都为开头),结尾变量遍历过程中如果这个数是第一次出现的(用 map 映射判断是不是等于 0 )就增加这一页,同时用 num 统计遍历过程中的种类,当 num == n,说明这个长度内的数已经能访问所有的数种,这时候开始移动头变量,如果删除这个数后剩下这个数种的数量仍然大于 0,说明没有影响,当删除到这一个数出现数种 == 0 的时候再移动尾变量。不断循环这个过程就能找到一个最小的长度。

 

       AC:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <set>
#include <map>

using namespace std;

const int MAXN = 1000005;

int num[MAXN];
set<int> ans;
map<int, int> cnt;

int main() {
    int n;
    scanf("%d", &n);

    for (int i = 0; i < n; ++i) {
        scanf("%d", &num[i]);
        ans.insert(num[i]);
    }

    int sum = ans.size();
    int s = 0, t = 0, now = 0;
    int Min_len = n;

    for(;;) {
        while (t < n && now < sum) {
            if (cnt[ num[t++] ]++ == 0) {
                    ++now;
            }
        }

        if (now < sum) break;
        Min_len = min(Min_len, t - s);
        if (--cnt[ num[s++] ] == 0) {
            --now;
        }
    }

    printf("%d\n", Min_len);

    return 0;
}

 

 

你可能感兴趣的:(reading)