题目大意
对于一个仅包含字符 的字符串 而言,规定 是按如下方式构造的字符串 :
- 最初 是空串;
- 枚举 ,往 的尾部添加 个 字符
给定字符串 ,反复将 替换为 直至 串长度为 。问需要的操作步数。答案对 取模。
如何判断无解
我们可以发现如果两个大于一的数相邻,那么就会出现无限循环变长。
举个例子:
-
-
-
-
⋮
我们就可以判断了,如果两个大于一的数相邻就直接输出 -1。
暴力思路
怎么暴力,这个很好想吧。
就是按照题目的要求模拟。
正确思路
考虑倒推。
我们设 变量为需要变多少次, 为当前是多少, 为 的后面一个是多少。
首先我们考虑 当 等于一的时候,他是不是会增加 个 。所以,这里我们 给 加上 ,为什么要加一呢?因为我们要把它自己给加上。
如果 不为一,那么就 应为它后面一定是一。
时间复杂度:。
代码
#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;
}