BZOJ3172[TJOI2013] Words
Test instructions
Someone reads a paper, a paper is made up of many words. But he found that a word would appear many times in the paper, and now wondered how many times each word appeared in the paper. Note that there is a separation between the words in the paper. Number of words ≤200, length ≤1000000
Exercises
First, each word is inserted into the trie, through the sum[i]++ of the node, and then the Fail function, after the completion of the BFS sequence to maintain the sum[fail[i]]+=sum[i], and finally output the end of the first word of the character node sum value.
Code:
1#include <cstdio>2#include <cstring>3#include <algorithm>4 #defineMAXN 10000105 #defineInc (I,J,K) for (int i=j;i<=k;i++)6 using namespacestd;7 8 intch[maxn][ -],SUM[MAXN],POS[MAXN],Q[MAXN],N,TOT,FAIL[MAXN];CharS[MAXN];9 intInsertChar*s) {Ten intL=strlen (s+1), x=0; OneInc (I,1, l) {if(!ch[x][s[i]-'a']) ch[x][s[i]-'a']=++tot; x=ch[x][s[i]-'a']; sum[x]++;}returnx; A } - voidGetfail () { - intL=1, r=0; Inc (I,0, -)if(ch[0][i]) q[++r]=ch[0][i],fail[ch[0][i]]=0; the while(l<=R) { - intx=q[l++]; -Inc (I,0, -)if(Ch[x][i]) { - intY=FAIL[X]; while(Y&&!ch[y][i]) y=Fail[y]; + if(Ch[y][i]) fail[ch[x][i]]=ch[y][i]; q[++r]=Ch[x][i]; - } + } A for(inti=r;i;i--) sum[fail[q[i]]]+=Sum[q[i]]; at } - intMain () { -scanf"%d", &n); tot=0; Inc (I,1, n) {scanf ("%s", s+1); pos[i]=insert (s);} -Getfail (); Inc (I,1, N) printf ("%d\n", Sum[pos[i]]); -}
20160620
BZOJ3172[TJOI2013] Words