Test instructions: Multiple template strings, a text string, find that those template strings appear in the text string most times.
Solution: The introduction of AC automata template problem.
Code:
#include <iostream>#include<cstdio>#include<cstring>#include<cstdlib>#include<cmath>#include<algorithm>#include<string>#include<vector>#include<queue>#include<map>#defineMod 1000000007using namespacestd;#defineN 1000007Const intMaxnode =20005;Const intSIZE = -;intCnt[maxnode];structTrie {intCh[maxnode][size],val[maxnode],sz,fail[maxnode],last[maxnode]; Trie () {sz=1; memset (ch[0],0,sizeof(ch[0])); } intIdxCharc) {returnC-'a'; }; voidInit () {sz =1; memset (ch[0],0,sizeof(ch[0])); memset (CNT,0,sizeof(CNT)); } voidPrintintj) {if(j) {Cnt[val[j]]++; Print (Last[j]); } return; } voidInsert (Char*s,intv) {intU =0, n =strlen (s); for(intI=0; i<n;i++) { intc =idx (s[i]); if(!Ch[u][c]) {memset (Ch[sz],0,sizeof(Ch[sz])); VAL[SZ]=0; CH[U][C]= sz++; } u=Ch[u][c]; } Val[u]=v; } voidGetfail () {Queue<int>Q; fail[0] =0; for(intC=0; c<size;c++) { intU = ch[0][c]; if(u) {fail[u] =0; Q.push (U); Last[u] =0; } } while(!Q.empty ()) { intR =Q.front (); Q.pop (); for(intC=0; c<size;c++) { intU =Ch[r][c]; if(!u)Continue; Q.push (U); intv =Fail[r]; while(v &&!ch[v][c]) v =Fail[v]; Fail[u]=Ch[v][c]; Last[u]= Val[fail[u]]?Fail[u]: last[fail[u]; } } } voidQueryChar*T) {intn = strlen (T), j =0; for(intI=0; i<n;i++) { intc =idx (t[i]); while(J &&!ch[j][c]) j =Fail[j]; J=Ch[j][c]; if(Val[j]) print (j); Else if(Last[j]) print (last[j]); } }};Chart[n],ss[ the][ the];map<string,int>MP; Trie AC;intMain () {intN,i; while(SCANF ("%d", &n)!=eof &&N) {mp.clear (); Ac.init (); for(i=1; i<=n;i++) {scanf ("%s", Ss[i]); Ac. Insert (Ss[i],i); mp[string(Ss[i]) =i; } ac.getfail (); scanf ("%s", T); Ac.query (T); intMaxi =-1; for(i=1; i<=n;i++) Maxi=Max (maxi,cnt[i]); cout<<Maxi<<Endl; for(i=1; i<=n;i++) { if(cnt[mp[string(Ss[i])] ==Maxi) printf ("%s\n", Ss[i]); } } return 0;}View Code
Uvalive 4670 dominating Patterns--ac automatic machine first question