ABC 313 E题 题解

· · 题解

题目大意

对于一个仅包含字符 1,2,3,4,5,6,7,8,9 的字符串 S 而言,规定 f(S) 是按如下方式构造的字符串 T:

给定字符串 S,反复将 S 替换为 f(S) 直至 S 串长度为 1。问需要的操作步数。答案对 998244353 取模。

如何判断无解

我们可以发现如果两个大于一的数相邻,那么就会出现无限循环变长。

举个例子:

我们就可以判断了,如果两个大于一的数相邻就直接输出 -1。

暴力思路

怎么暴力,这个很好想吧。

就是按照题目的要求模拟。

正确思路

考虑倒推。

我们设 res 变量为需要变多少次,x 为当前是多少,y 为 x 的后面一个是多少。

首先我们考虑 当 x 等于一的时候,他是不是会增加 y-1 个 x。所以,这里我们 给 res 加上 (y-1) \times res+1,为什么要加一呢?因为我们要把它自己给加上。

如果 x 不为一,那么就 res+1 应为它后面一定是一。

时间复杂度:O(N)。

代码


#include <bits/stdc++.h>
#define TNTMAX INT_MAX
#define db double
#define ll long long
#define ex exit(0);
using namespace std;
ll mod = 998244353;
int main() {
    //freopen(".in","r",stdin);
    //freopen(".out","w",stdout);
    ll n;
    cin >> n;
    string s;
    cin >> s;
    ll res = 0;
    for (int i = n - 1; i > 0; i--) {
        if (s[i] != '1' && s[i - 1] != '1') {
            cout << "-1";
            return 0;
        }
        ll x = s[i] - '0', y = 0;
        if (i != n + 1) {
            y = s[i + 1] - '0';
        }
        if (x == 1) {
            if (i != n - 1) {
                res = (res + (y - 1) * res % mod + 1) % mod;
            } else {
                res++;
            }
        } else {
            res++;
        }
        res %= mod;
    }
    res += (s[1] - '0' - 1) * res % mod;
    res %= mod;
    res = (res + mod) % mod;
    cout << res;
    return 0;
}


AT的AC记录