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

· · 算法·理论

0x01 Problem

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

样例输入

bab

样例输出

2

0x02 Solution

暴力

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

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

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

时间复杂度 O(n^2)

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

#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;
}

正解

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

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

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

A_{r} - A_{l-1}

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

B_{r} - B_{l-1}

\mathfrak{Code\,Here}

#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;
}