题目链接<http://codeforces.com/gym/100971/problem/M>
题意:
给出一个字符串,把这个字符串分成m段,段与段之间首尾相连。每段中包含的不同的字母个数恰好为k,问m最小是多少。
题解:
这里介绍一位神犇的O(n)算法。
设一个num数组记录当前段中,各个字符出现的个数;cnt表示所选字符串不同字符的个数。dp[i]数组表明字符串第i个字符以前的答案。
1、枚举以第i个字符为结尾的情况。在i之后开始找一段出现k个字符的字符串。
2、再记一个变量stp往找到的字符串之后继续找,如果stp表示的字符在当前所选串中出现过,那么以那个字符结尾的答案也可以得出。
3、最后用取尺法舍去区间中第一个字符,num减去这个字符的,判断是否cnt减少。然后回到第一个步骤
整个算法stp是一直往后的,i也是往后枚举的,算法复杂度就是O(n)。详细看代码。
#include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <set>
#include <map>
#include <string>
#include <queue>
#include <stack>
#include <string>
using namespace std;
typedef long long LL;
using namespace std;
const int N=2e5+7;
int dp[N],num[N];
int k,stp,cnt;
char s[N];
int main(){
scanf("%d",&k);
scanf("%s",s+1);
int n=strlen(s+1);
memset(dp,-1,sizeof(dp));
dp[0]=0;
for(int i=1;i<=n;i++){
while(cnt<k&&stp<n){
stp++;
if(num[s[stp]]==0) cnt++;
num[s[stp]]++;
}
if(dp[i-1]!=-1&&cnt==k){
if(dp[stp]==-1) dp[stp]=dp[i-1]+1;
while(stp<n){
if(num[s[stp+1]]==0) break;
dp[++stp]=dp[i-1]+1;
num[s[stp]]++;
}
}
printf("%d ",dp[i]);
if(num[s[i]]==1) cnt--;
num[s[i]]--;
}
printf("\n");
}