版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
题意: 给你两个字符串 t 和 s,然后让你计算 s的后缀在 t中出现的次数* 后缀的长度 累加的 和 。
思路:
考虑KMP ,因为 KMP 是匹配前缀的所以,需要倒转字符串。
然后设dp数组为 长度 为 i的前缀 在 t中出现 的次数 ,在 KMP 匹配的过程中,每次 dp[j] ++。但是,KMP算法为了减少 回溯,会省略相同长度字符的匹配,即Next[i] 代表着非前缀 后缀的 子串 与 该字符串前缀 匹配的最大长度,如果Next[i]非零,i 长度的 前缀 必然包含一个长度为Next[i] 的前缀 和 整个字符串的前缀匹配。
即 dp[Next[i]] += dp[i]
AC Code:
#include<iostream>
#include<cstring>
#include<queue>
#include<map>
#include<set>
#include<stack>
#include<cmath>
#include<cstdio>
#include<iomanip>
#include<sstream>
#include<algorithm>
using namespace std;
#define read(x) scanf("%d",&x)
#define Read(x,y) scanf("%d%d",&x,&y)
#define sRead(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define gc(x) scanf(" %c",&x);
#define mmt(x,y) memset(x,y,sizeof x)
#define write(x) printf("%d\n",x)
#define INF 0x3f3f3f3f
#define ll long long
const ll mod = 1e9 + 7;
#define pdd pair<double,double>
const int N = 1e6+5;
int Next[N];
char s[N];
char t[N];
ll dp[N];
void kmp_pre(int m){
int i = 0,j = Next[0] = -1;
while(i < m){
while(j != -1&& s[i] != s[j]) j = Next[j];
Next[++i] = ++j;
}
}
void kmp(int n,int m){
kmp_pre(m);
int i = 0,j= 0;
while(i < n){
while(j != -1&&t[i] != s[j]) j = Next[j];
++i,++j;
dp[j]++;
}
}
int main()
{
int T;
read(T);
while(T--){
mmt(dp,0);
mmt(Next,0);
scanf("%s%s",t,s);
int n = strlen(t);
int m = strlen(s);
reverse(t,t+n);
reverse(s,s+m);
kmp(n,m);
ll ans = 0;
for(int i = m;i >= 1;--i){
dp[Next[i]] += dp[i];
}
for(int i = 1;i <= m;++i){
ans += dp[i] * i;
ans %= mod;
}
cout<<ans<<endl;
}
}