Codeforces Round #364 (Div. 2)C They Are Everywhere(尺取法)

题目链接: 传送门

They Are Everywhere

time limit per test:2 second     memory limit per test:256 megabytes

Description

Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n - 1.
There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once.
Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit.

Input

The first line contains the integer n (1 ≤ n ≤ 100 000) — the number of flats in the house.
The second line contains the row s with the length n, it consists of uppercase and lowercase letters of English alphabet, the i-th letter equals the type of Pokemon, which is in the flat number i.

Output

Print the minimum number of flats which Sergei B. should visit in order to catch Pokemons of all types which there are in the house.

Sample Input

3
AaA



7
bcAAcbc


6
aaBCCe

Sample Output

2

3

5

解题思路

题目大意:给一串字符串,问包含字符串中所有字符种类的区间最小长度。
类型题POJ 3320
假设从某一位置,为了覆盖所有种类字符串需要到t位置,这样的话可以知道如果从s+1开始开始的话,那么必须到t'位置为止。由此可以考虑尺取法。

#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<algorithm>
#include<cstring>
using namespace std;

int main()
{
	int N;
	char str[100005];
	set<char>all;
	memset(str,0,sizeof(str));
	scanf("%d",&N);
	scanf("%s",str);
	for (int i = 0;i < N;i++)
	{
		all.insert(str[i]);
	}
	int n = all.size();
	int s = 0,t = 0,num = 0;
	map<char,int>count;
	int res = N;
	for (;;)
	{
		while (t < N && num < n)
		{
			if (count[str[t++]]++ == 0)
			{
				num++;
			}
		}
		if (num < n)
			break;
		res = min(res,t-s);
		if (--count[str[s++]] == 0)
		{
			num--;
		}
	}
	printf("%d\n",res);
	return 0;
}
posted @ 2016-07-23 21:58  zxzhang  阅读(221)  评论(0)    收藏  举报