Description
一篇论文是由许多单词组成但小张发现一个单词会在论文中出现很多次,他想知道每个单词分别在论文中出现了多少次。
Sample Input
3
a
aa
aaa
Sample Output
6
3
1
这道题,AC自动机裸题。。。
你建好AC自动机,再把所有s从最底层和上来。
#include <cstdio>
#include <cstring>
using namespace std;
int _max(int x, int y) {return x > y ? x : y;}
const int maxn = 1100000;
struct node {
int pp, s, fail, v[30];
node() {memset(v, -1, sizeof(v));}
} t[maxn]; int cnt, list[maxn];
int cc[maxn];
char ss[maxn];
void bt(int now) {
int x = 0;
int len = strlen(ss + 1);
for(int i = 1; i <= len; i++) {
int y = ss[i] - 'a' + 1;
if(t[x].v[y] == -1) t[x].v[y] = ++cnt;
t[x].s++; x = t[x].v[y];
} t[x].s++;
cc[now] = x;
}
void get_fail() {
int head = 1, tail = 2;
list[1] = 0;
while(head != tail) {
int x = list[head];
for(int i = 1; i <= 26; i++) {
int y = t[x].v[i];
if(y == -1) continue;
if(x == 0) t[y].fail = 0;
else {
int j = t[x].fail;
while(j && t[j].v[i] == -1) j = t[j].fail;
t[y].fail = _max(0, t[j].v[i]);
}
list[tail++] = y;
}
head++;
}
for(int i = tail; i >= 1; i--) t[t[list[i]].fail].s += t[list[i]].s;
}
int main() {
int n; scanf("%d", &n);
for(int i = 1; i <= n; i++) {
scanf("%s", ss + 1);
bt(i);
}
get_fail();
for(int i = 1; i <= n; i++) printf("%d\n", t[cc[i]].s);
return 0;
}