Link to the question: Ultraviolet A 1358-generator
Given N, it indicates there are n characters, and then given a string S, the string is empty at the beginning, and now a 1 ~ N is added to the end of the string, and the string contains s as the expected number of times the substring is generated.
Solution: first, we need to pre-process s to find out the mismatch array.
The definition of DP [I] indicates that the end part matches the expected number of times required by the I s string. Each enumeration may contain 1 ~ N. For the S string, I + 1 must be a definite character, so other characters certainly do not match.
Assuming that the K character is generated and the K character is not equal to s [I + 1], we can determine the number of matching Characters Based on the S mismatch array, (similar to the KMP matching problem). Suppose there are j matching characters, that is to say, we need to re-generate DP [I]-DP [J] times from matching J to matching I (expected ).
So f (I) (from matching I-1 to matching I need to generate the expected number of times) There is a formula f (I) = 1 + Σ I = 1N (DP [I? 1]? DP [lose (k)]) + n? 1nf (I) (lose (k) is the number of matched characters when the corresponding generated character is K)
DP [I] = DP [I-1] + f (I)
#include <cstdio>#include <cstring>#include <algorithm>using namespace std;typedef long long ll;const int maxn = 20;int len, jump[maxn];void get_jump(char* s) { int p = 0; len = strlen(s+1); for (int i = 2; i <= len; i++) { while (p && s[p+1] != s[i]) p = jump[p]; if (s[p+1] == s[i]) p++; jump[i] = p; }}ll solve () { int n; ll dp[maxn]; char s[maxn]; scanf("%d%s", &n, s+1); get_jump(s); dp[0] = 0; for (int i = 1; i <= len; i++) { ll& ans = dp[i]; ans = dp[i-1] + n; for (int j = 0; j < n; j++) { if (s[i] == ‘A‘ + j) continue; int p = i-1; while (p && s[p+1] != j + ‘A‘) p = jump[p]; if (s[p+1] == j + ‘A‘) p++; ans += dp[i-1] - dp[p]; } } return dp[len];}int main () { int cas; scanf("%d", &cas); for (int kcas = 1; kcas <= cas; kcas++) { printf("Case %d:\n%lld\n", kcas, solve()); if (kcas < cas) printf("\n"); } return 0;}
Ultraviolet A 1358-generator (KMP + expected)