嘟嘟嘟
SAM。
把第一个串建成后缀自动机,然后放第二个串上去跑。
匹配到了一个节点,对答案的贡献应该是这个点到根节点的路径上的所有节点代表的字符串个数乘以对应的出现次数之和。
每一个点代表的字符串个数就是(len[p] - len[link[p]]),出现次数就是(size[p]),而到根节点的这个和可以预处理出来。
需要注意的是,对于当前节点不能都选,因为可能该节点代表的字符串的最长长度大于当前匹配长度(l),所以应该加上的是((l - len[link[p]]) * size[p])。
#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
#define enter puts("")
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define In inline
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
const int maxn = 2e5 + 5;
inline ll read()
{
ll ans = 0;
char ch = getchar(), last = ' ';
while(!isdigit(ch)) last = ch, ch = getchar();
while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
if(last == '-') ans = -ans;
return ans;
}
inline void write(ll x)
{
if(x < 0) x = -x, putchar('-');
if(x >= 10) write(x / 10);
putchar(x % 10 + '0');
}
char s1[maxn], s2[maxn];
struct Sam
{
int las, cnt;
int tra[maxn << 1][30], len[maxn << 1], link[maxn << 1], endp[maxn << 1];
In void init() {link[las = cnt = 0] = -1;}
In void insert(int c)
{
int now = ++cnt, p = las;
len[now] = len[las] + 1; siz[now] = 1;
while(~p && !tra[p][c]) tra[p][c] = now, p = link[p];
if(p == -1) link[now] = 0, endp[now] = 1;
else
{
int q = tra[p][c];
if(len[q] == len[p] + 1) link[now] = q, endp[now] = endp[q] + 1;
else
{
int clo = ++cnt;
memcpy(tra[clo], tra[q], sizeof(tra[q]));
len[clo] = len[p] + 1; endp[clo] = endp[p] + 1;
link[clo] = link[q], link[q] = link[now] = clo;
endp[q] = endp[now] = endp[clo] + 1;
while(~p && tra[p][c] == q) tra[p][c] = clo, p = link[p];
}
}
las = now;
}
int buc[maxn << 1], pos[maxn << 1], siz[maxn << 1];
ll sum[maxn << 1];
In void dfs()
{
for(int i = 1; i <= cnt; ++i) ++buc[len[i]];
for(int i = 1; i <= cnt; ++i) buc[i] += buc[i - 1];
for(int i = 1; i <= cnt; ++i) pos[buc[len[i]]--] = i;
for(int i = cnt; i; --i) siz[link[pos[i]]] += siz[pos[i]];
for(int i = 1; i <= cnt; ++i)
{
int now = pos[i], fa = link[now];
sum[now] = sum[fa] + 1LL * (len[now] - len[fa]) * siz[now];
}
}
In ll solve(char* s)
{
int m = strlen(s);
ll ret = 0;
for(int i = 0, p = 0, l = 0; i < m; ++i)
{
int c = s[i] - 'a';
while(~p && !tra[p][c]) p = link[p], l = len[p];
if(p == -1) p = l = 0;
else p = tra[p][c], ++l, ret += sum[link[p]] + 1LL * (l - len[link[p]]) * siz[p];
}
return ret;
}
}S;
int main()
{
scanf("%s%s", s1, s2);
int n = strlen(s1); S.init();
for(int i = 0; i < n; ++i) S.insert(s1[i] - 'a');
S.dfs();
write(S.solve(s2)), enter;
return 0;
}