标签:https pos puts tps sizeof vector get algorithm har
嘟嘟嘟
现在看到字符串就想到SAM,所以很担心kmp啥的会不会忘了……
这题感觉挺暴力的:首先当然要把\(s\)建成SAM,然后令\(dp[i][j]\)表示到第\(i\)组时,SAM上节点\(j\)能匹配的字符串个数。
转移的时候暴力枚举起点节点\(p\),然后每一次都把当前字符串放上去跑,如果在SAM上存在的话,令结束节点为\(x\),则有\(dp[i][x] += dp[i - 1][p]\)。
那么最后的答案就是\(\sum _ {i = 1} ^ {cnt} dp[m][i] * size[i]\)。
然后开一个临时数组就可以把dp降维了。
理论上\(O(|S| + ka_i |s|)\)的复杂度,实际上跑的飞快,挤到了loj rank3。
#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 ll mod = 1e9 + 7;
const int maxn = 1e4 + 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');
}
int m;
char s[maxn];
In ll inc(ll a, ll b) {return a + b >= mod ? a + b - mod : a + b;}
struct Sam
{
int las, cnt;
int tra[maxn << 1][26], len[maxn << 1], link[maxn << 1], siz[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;
else
{
int q = tra[p][c];
if(len[q] == len[p] + 1) link[now] = q;
else
{
int clo = ++cnt;
memcpy(tra[clo], tra[q], sizeof(tra[q]));
len[clo] = len[p] + 1;
link[clo] = link[q], link[q] = link[now] = clo;
while(~p && tra[p][c] == q) tra[p][c] = clo, p = link[p];
}
}
las = now;
}
char s[maxn];
In int tour(int p, char* s)
{
int len = strlen(s);
for(int i = 0, c; i < len; ++i)
if(tra[p][c = s[i] - 'A']) p = tra[p][c];
else return -1;
return p;
}
int dp[maxn << 1] = {1}, tp[maxn << 1];
In void solve()
{
fill(tp, tp + cnt + 1, 0);
int T = read();
while(T--)
{
scanf("%s", s);
for(int i = 0; i <= cnt; ++i)
if(dp[i])
{
int v = tour(i, s);
if(~v) tp[v] = inc(tp[v], dp[i]);
}
}
for(int i = 0; i <= cnt; ++i) dp[i] = tp[i];
}
int buc[maxn << 1], pos[maxn << 1];
In ll calc()
{
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;
ll ret = 0;
for(int i = cnt; i; --i)
{
int now = pos[i], fa = link[now];
siz[fa] += siz[now];
ret = inc(ret, 1LL * dp[now] * siz[now] % mod);
}
return ret;
}
}S;
int main()
{
m = read(); scanf("%s", s);
int len = strlen(s); S.init();
for(int i = 0; i < len; ++i) S.insert(s[i] - 'A');
for(int i = 1; i <= m; ++i) S.solve();
write(S.calc());
return 0;
}
标签:https pos puts tps sizeof vector get algorithm har
原文地址:https://www.cnblogs.com/mrclr/p/10553770.html