题目链接:CF 701C
题面:
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.
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.
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.
3 AaA
2
7 bcAAcbc
3
6 aaBCCe
5
In the first test Sergei B. can begin, for example, from the flat number 1 and end in the flat number 2.
In the second test Sergei B. can begin, for example, from the flat number 4 and end in the flat number 6.
In the third test Sergei B. must begin from the flat number 2 and end in the flat number 6.
题意:
给定一串仅由大小写字母组成的字符串,问其最短的连续子串可以包含母串所有元素的串长。
解题:
采用的是O(nlogn*52)的复杂度方法,计算前缀和,枚举左端点,二分右端点,每次比较是否包含了所有元素,进行区间移动,求最优值。虽然只用了139ms,但更快的方法是31ms。这题和POJ 3320是一样的,但POJ那题,n更大,为1000000,二分的复杂度是O(n(logn)^2)是过不了的,正确的解法是O(nlogn),左端点先设为1,先找到一个区间包含全部元素,随后不断调整左右端点,寻找最小长度(过程中用map维护),详解可看:POJ 3320 详解。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <map>
#define LL long long
using namespace std;
int cnt[100010][52];
bool vis[52];
char s[100010];
int main()
{
int n,len,am=0,tmp,le,ri,tcnt,ans=1000000;
scanf("%d",&n);
scanf("%s",s);
len=strlen(s);
if(s[0]<='Z')
tmp=s[0]-'A';
else
tmp=s[0]-'a'+26;
cnt[1][tmp]++;
vis[tmp]=1;
for(int i=1;i<len;i++)
{
for(int j=0;j<52;j++)
cnt[i+1][j]=cnt[i][j];
if(s[i]<='Z')
tmp=s[i]-'A';
else
tmp=s[i]-'a'+26;
cnt[i+1][tmp]++;
vis[tmp]=1;
}
for(int i=0;i<52;i++)
if(vis[i])
am++;
for(int i=0;i<n;i++)
{
le=i;
ri=n-1;
bool flag=0;
while(le<=ri)
{
tcnt=0;
int mid=(le+ri)>>1;
for(int j=0;j<52;j++)
{
if(vis[j])
{
tmp=cnt[mid+1][j]-cnt[i][j];
if(tmp)
tcnt++;
}
}
if(tcnt==am)
{
tmp=mid-i+1;
flag=1;
if(tmp<ans)
ans=tmp;
ri=mid-1;
}
else
le=mid+1;
}
if(!flag)
break;
}
printf("%d\n",ans);
return 0;
}