传送门:洛谷 - P3966
思路分析
由于每个模式串都在文本串内,所以在插入每个模式串的时候,记录到达每个节点的次数,然后建fail树求子树大小
AC代码
#include <bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define fun function
#define sz(x) (int)(x).size()
#define lowbit(x) (x)&(-x)
#define all(x) (x).begin(),(x).end()
#define mem(a,b) memset(a,b,sizeof(a))
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
namespace FastIO {
#define BUF_SIZE 100000
#define OUT_SIZE 100000
bool IOerror=0;
inline char nc() {
static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE;
if(p1==pend) {
p1=buf;
pend=buf+fread(buf,1,BUF_SIZE,stdin);
if(pend==p1) {
IOerror=1;
return -1;
}
}
return *p1++;
}
inline bool blank(char ch) {
return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';
}
template<class T> inline bool read(T &x) {
bool sign=0;
char ch=nc();
x=0;
for(; blank(ch); ch=nc());
if(IOerror)return false;
if(ch=='-')sign=1,ch=nc();
for(; ch>='0'&&ch<='9'; ch=nc())x=x*10+ch-'0';
if(sign)x=-x;
return true;
}
template<class t> inline void print(t x) {
if (x < 0) putchar('-'), print(-x);
else {
if (x > 9) print(x / 10);
putchar('0' + x % 10);
}
}
template<class T,class... U>bool read(T& h,U&... t) {
return read(h)&&read(t...);
}
#undef OUT_SIZE
#undef BUF_SIZE
};
using namespace std;
using namespace FastIO;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
typedef long long ll;
typedef pair<int,int> pii;
typedef unsigned long long ull;
const int INF = 0x3f3f3f3f;
const int N = 2e6+10;
int match[N];
vector<int>e[N];
int siz[N];
void dfs(int u) {
for(auto v:e[u]) {
dfs(v);
siz[u]+=siz[v];
}
}
struct AC_auto {
struct T {
int son[26],fail,word;
void clear() {
mem(son,0);
word = fail = 0;
}
} tree[N];
int cnt = 1;
int newnode() {
++cnt;
tree[cnt].clear();
return cnt;
}
void init() {
cnt = 1;
tree[1].clear();
}
void ins(string s,int id) {
int p = 1;
for(auto i:s) {
int c = i-'a';
if(!tree[p].son[c]) tree[p].son[c] = newnode();
p = tree[p].son[c];
++siz[p];
}
match[id] = p;
}
void getfail() {
for(int i=0; i<26; i++) tree[0].son[i] = 1;
queue<int>q;
q.push(1);
while(!q.empty()) {
int u = q.front();
q.pop();
for(int i=0; i<26; i++) {
int v = tree[u].son[i];
int ufail = tree[u].fail;
if(v) {
tree[v].fail = tree[ufail].son[i];
q.push(v);
} else tree[u].son[i] = tree[ufail].son[i];
}
}
}
} AC;
signed main() {
#ifdef xiaofan
freopen("1.in","r",stdin);
freopen("1.out","w",stdout);
#endif
IOS;
int n;
cin>>n;
AC.init();
for(int i=1;i<=n;i++) {
string s;
cin>>s;
AC.ins(s,i);
}
AC.getfail();
for(int i=2;i<=AC.cnt;i++) e[AC.tree[i].fail].pb(i);
dfs(1);
for(int i=1;i<=n;i++) cout<<siz[match[i]]<<endl;
return 0;
}