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 @   zxzhang  阅读(216)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示

目录导航