Gym - 100971M - Decomposition into Good Strings - O(n)算法

题目链接<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");
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值