P4548 [CTSC2006] 歌唱王国 题解
happy_zero · · 题解
设计一个势能函数
考虑一个形象的比喻,在每一个字符被敲出来前,都有一个赌徒下赌注(不用花费代价),设其在
发现所有赌徒的期望收益其实就可以作为一个势能函数,因为有
显然有
实现就直接用 KMP 求 border 即可。
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int P = 1e4;
const int N = 1e5 + 5;
int a[N], nxt[N], p[N];
signed main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int m, n; cin >> m >> n; p[0] = 1;
for (int i = 1; i < N; i++)
p[i] = p[i - 1] * m % P;
for (int i = 1; i <= n; i++) {
int len; cin >> len;
for (int j = 1; j <= len; j++) cin >> a[j];
for (int j = 2; j <= len; j++) {
int k = nxt[j - 1];
while (k && a[k + 1] != a[j]) k = nxt[k];
nxt[j] = k + (a[k + 1] == a[j]);
}
int now = nxt[len], ans = p[len];
while (now) (ans += p[now]) %= P, now = nxt[now];
string s = to_string(ans);
for (int j = 1; j <= 4 - s.size(); j++)
cout << 0; cout << s << '\n';
}
return 0;
}