题解:ABC456C

· · 题解

问题描述

给定一个仅由 a、b、c 组成的字符串 S,长度 n 最大为 3\times10^5。要求统计所有 非空子串 中,满足 子串内任意两个相邻字符都不相同 的子串个数。两个子串只要起始位置不同就视为不同(即使内容相同)。

解题思路

直接枚举所有子串并检查的复杂度为 O(n^3) 或 O(n^2),不可接受。我们需要 O(n) 的解法。

动态规划定义

设:

转移方程

考虑字符 S_i:

边界条件

对于第一个字符 i=0,没有前驱,显然 dp_0 = 1。

::::success[AC Code]

#include <bits/stdc++.h>
#define int long long
using namespace std;

const int mod = 998244353;

signed main() {
    string s;
    cin >> s;
    int res = 1, pre_cnt = 1;
    for (int i = 1, t; i < (int)s.size(); i++)
        t = (s[i] != s[i - 1] ? pre_cnt + 1 : 1), (res += t) %= mod, pre_cnt = t;
    cout << res % mod;
    return 0;
}

::::