跳到正文

算法·理论

[深入浅出学算法][递推专题] 字母a和b的故事 题解

Carey_chen约 5 分钟
原文
文章信息与版本

文章信息

发布
2023年7月6日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 5 分钟

版本

  1. v1当前

0x01 Problem

字母 aa 和 bb 作为字母表的老大和老二,一直在字母届称王称霸,完美字符串因为它们运营而生。完美字符串只包含字母 aa 和字母 bb ,并且串为 ABA\text{ABA} 的形式, A\text{A} 代表只有字母 aa 的集合,字母 B\text{B} 代表只有字母 bb 的集合,当然,这些集合都可以为空。 现在可以对给定串进行任意次数的删减,但顺序不准改变,求出最长的完美串长度。

样例输入

代码
bab

样例输出

代码
2

0x02 Solution

暴力

我们注意到,由于可以删减任意次数,最优解也相当于 “把串分为 33 段,求第一段 aa 的数量, 第二段 bb 的数量,第三段 aa 的数量,求它们的最大和。”

这启发我们用 “隔板法” 解决问题。枚举 “板” 的位置,分割字符串,统计每段内字符的数量即可。

注意:由于集合都可以为空,两个“板”可以放在一起。

时间复杂度 O(n2)O(n^2)

Code Here (32pts)\mathfrak{Code\,Here\,(32pts)}

C++
#include <bits/stdc++.h>
 
char s[3010];
int n;
 
int count(int l, int r, char x)
{
    int cnt = 0, ans = 0;
     
    for(int i = l; i <= r; i++)
    {
        if(s[i] == x)
        {
            cnt++;
        }
        else
        {
            ans = std::max(ans, cnt);
            cnt = 0;
        }
    }
     
    ans = std::max(ans, cnt);
     
    return ans;
}
 
int main()
{
    int ans = 1;
     
    scanf("%s", s);
     
    n = strlen(s);
    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j <= n; j++)
        {
            ans = std::max(ans, count(1, i, 'a') + count(i, j, 'b') + count(j, n, 'a'));
        }
    }
     
    printf("%d", ans);
     
    return 0;
}

正解

考虑优化暴力思路,在 “统计每段内字符的数量” 时,可以使用“前缀和” 方法,设有AiA_{i} 为 1∼i1 \sim i 内 ‘a’ 的数量,BiB_{i} 为 1 i1 ~ i 内 ‘b’ 的数量,有

第 i 个字符为 a 时{Ai=Ai−1+1(个数增加1)Bi=Bi−1(个数不变) 第\,i\,个字符为\,a\,时 \begin{cases} A_{i} = A_{i-1}+1 \quad (个数增加1)\\ B_{i} = B_{i-1}\quad (个数不变) \end{cases} 第 i 个字符为 b 时{Ai=Ai−1(个数不变)Bi=Bi−1+1(个数增加1) 第\,i\,个字符为\,b\,时 \begin{cases} A_{i} = A_{i-1} \quad (个数不变)\\ B_{i} = B_{i-1}+1\quad (个数增加1) \end{cases}

那么, [l,r][l, r] 内 aa 的数量为

Ar−Al−1A_{r} - A_{l-1}

同理, [l,r][l, r] 内 bb 的数量为

Br−Bl−1B_{r} - B_{l-1}

Code Here\mathfrak{Code\,Here}

C++
#include <bits/stdc++.h>
 
int n;
char s[3010];
int dpA[3010], dpB[3010];
 
void init()
{
    for(int i = 0; i < n; i++)
    {
        if(s[i] == 'a')
        {
            dpA[i] = dpA[i-1] + 1;
            dpB[i] = dpB[i-1];
        }
        else
        {
            dpA[i] = dpA[i-1];
            dpB[i] = dpB[i-1] + 1;
        }
    }
}
 
int count(int l, int r, char x)
{
    if(x == 'a')
    {
        return dpA[r] - dpA[l-1];
    }
    else
    {
        return dpB[r] - dpB[l-1];
    }
}
 
int main()
{
    int ans = 1;
     
    scanf("%s", s);
     
    n = strlen(s);
     
    init();
 
    for(int i = 0; i < n; i++)
    {
        for(int j = i; j < n; j++)
        {
            if(j != 0 && i != n-1)
            {
                ans = std::max(ans, count(0, i-1, 'a') + count(i, j, 'b') + count(j+1, n-1, 'a'));
            }
            else
            {
                ans = std::max(ans, count(0, n-1, 'a'));
            }
        }  
    }
     
    printf("%d", ans);
     
    return 0;
}
原文