题解:P11959 「ZHQOI R1」诗歌
不难发现只需要考虑长度为 2 和 3 的回文串。为了得到一个长度为 2 的回文串,我们需要将两个相同字符中间的所有字符删除。为了得到一个长度为 3 的回文串,我们需要将两个相同字符中间删到只剩一个字符。从而合法条件就是任意两个相同字符的距离
假设我们已经指定了结尾字符(可以理解为
我们设
那么转移对于所有的结尾字符都是一样的:
- 要么放一个不是结尾字符,也不是前面
m+2 个字符中的任意一个的字符,转移为(k-m-3)f_i \to f_{i+1} 。 - 要么放一个结尾字符,并放
m+2 个不是结尾字符的字符。这些字符只需要让它们与前面m+2 个字符不同就自然不是结尾字符了。从而转移为(k-m-2)^{m+2}f_i \to f_{i+m+3} 。
初始状态和结尾字符有关。具体来说:
- 如果是
m+3 ,则初始状态是f_{m+2}=1 。 - 否则记为
t ,那么我们需要先在t 后面填到m+2 个字符。初始状态是f_{m+2+t}=(k-m-2)^t 。
答案都是
注意到初始状态只是将整个 dp 数组平移了一下再整体乘了一个数值。于是我们只需要做一次 dp(不妨认为是用
采用哈希表,我们就可以线性地执行重标号,复杂度为
#include <bits/stdc++.h>
using namespace std;
const long long mod = 998244353;
const int N = 10100000;
int n, q, m;
long long k, f[N + 5];
inline long long Power(long long x, long long y) {
long long ans = 1;
while (y) {
if (y & 1) ans = ans * x % mod;
x = x * x % mod;
y >>= 1;
}
return ans;
}
int main() {
std::ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int _; cin >> _;
cin >> q >> k >> m;
f[m + 2] = 1;
long long p = Power(k - m - 2, m + 2);
for (int i = m + 3;i <= N;i++) f[i] = ((k - m - 3) * f[i - 1] + p * f[i - m - 3]) % mod;
for (int i = 1;i <= q;i++) {
map <int, int> idx;
int n;
cin >> n;
for (int j = 1;j <= m + 2;j++) {
int x;
cin >> x;
idx[x] = j;
}
int su;
cin >> su;
long long ans = 0;
while (su--) {
int u;
cin >> u;
if (idx[u] == 0) {
ans = (ans + f[n - 1]) % mod;
} else {
ans = (ans + f[n - 1 - idx[u]] * Power(k - m - 2, idx[u])) % mod;
}
}
cout << ans << endl;
}
return 0;
}