Source: Light OJ 1334 Genes in DNA
The prefix and suffix of the input text string and pattern string (n-1) * (n-1) how many times does a substring of a combined mode string appear before and after the combination of a substring can correspond to multiple combination strings?
Train of Thought: since it is a combination of prefix and suffix, it is very good to think of two positive and negative KMP enumeration adjacent two character I, j is the sum of the products of the number of prefixes ending with I multiplied by the number of suffixes starting with j.
The number of prefixes until I is almost the same as HDU 3336 DP.
The number of suffixes starting with the j character is sent and the prefix is the same.
#include
#include
#include
#include using namespace std;const int maxn = 50010;int l[maxn], r[maxn], f[maxn];int dp1[maxn], dp2[maxn];char s1[maxn], s2[maxn];void getFail(char *p, int *dp){int m = strlen(p);f[0] = f[1] = 0;dp[0] = 0;dp[1] = 1;for(int i = 1; i < m; i++){int j = f[i];while(j && p[i] != p[j])j = f[j];f[i+1] = p[i] == p[j] ? j+1 : 0;dp[i+1] = p[i] == p[j] ? dp[j+1]+1 : 1;}}void find(char *s1, char* s2, int* dp, int* a){int cnt = 0;int j = 0;int n = strlen(s1);int m = strlen(s2);for(int i = 0; i < n; i++){while(j && s1[i] != s2[j])j = f[j];if(s1[i] == s2[j])j++;a[i+1] = dp[j];if(j == m){a[i+1]--;j = f[j];} }}int main(){int cas = 1;int T;scanf("%d", &T);while(T--){scanf("%s %s", s1, s2);int n = strlen(s1);int m = strlen(s2);getFail(s2, dp1);find(s1, s2, dp1, l);reverse(s1, s1+n);reverse(s2, s2+m);getFail(s2, dp2);find(s1, s2, dp2, r);long long ans = 0;for(int i = 1; i < n; i++){ans += (long long)l[i]*r[n-i];}printf("Case %d: %lld\n", cas++, ans);}return 0;}