DP[I][J] Indicates the probability of walking the I step to the J node. Initial value dp[0][0] = 1. When you go to a node that is not the end of the word, you can walk past it.
!end[i]&&Last[i] = = Root , this node is only feasible.
1#include <bits/stdc++.h>2 using namespacestd;3 Const intN =505;4 intIdCharc) {5 if(c >='0'&&c <='9')returnC-'0';6 if(c >='a'&&c <='Z')returnC-'a'+Ten;7 if(c >='A'&&c <='Z')returnC-'A'+ $;8 return-1;9 }Ten structtire{ One intnex[n][ +], Fail[n],end[n], last[n]; A introot, L; - intNewNode () { -memset (Nex[l],-1,sizeof(Nex[l])); theEND[L] =0; - returnl++; - } - voidinit () { +L =0; -Root =NewNode (); + } A voidInsertChar*s) { at intnow =Root; - for(inti =0; T[n]; i++){ - intp =ID (s[i]); - if(Nex[now][p] = =-1) -NEX[NOW][P] =NewNode (); -now =Nex[now][p]; in } -End[now] =1; to } + voidbuild () { -queue<int>Q; theFail[root] = Last[root] =Root; * for(inti =0; I < +; i++){ $ int& u =Nex[root][i];Panax Notoginseng if(U = =-1) -U =Root; the Else{ +Fail[u] = Last[u] =Root; A q.push (u); the } + } - while(!Q.empty ()) { $ intnow =Q.front (); $ Q.pop (); - for(inti =0; I < +; i++){ - int& u =Nex[now][i]; the if(U = =-1) -U =nex[Fail[now]][i];Wuyi Else{ theFail[u] =nex[Fail[now]][i]; -Last[u] = end[Fail[u]]?Fail[u]: last[fail[u]; Wu q.push (u); - } About } $ } - } - }; - Tire ac; A Doublepor[ -]; + Chars[ -]; the Doubledp[ the][n]; - intMain () { $ intN, K, T, CA =1; scanf"%d", &t); the while(t--){ the ac.init (); thescanf"%d", &k); the for(inti =0; I < K; i++){ -scanf"%s", s); in Ac.insert (s); the } the ac.build (); Aboutmemset (Por,0,sizeof(POR)); thescanf"%d", &n); the Charch; the for(inti =0; I < n; i++){ +scanf"%c", &ch); - intp =ID (CH); thescanf"%LF", por+p);Bayi } the intL scanf"%d", &l); theMemset (DP,0,sizeof(DP)); -dp[0][0] =1; - for(inti =0; I < L; i++){ the for(intj =0; J < AC. L J + +) the if(Dp[i][j] >0) for(intK =0; K < +; k++){ the intRET =Ac.nex[j][k]; the if(!ac.end[ret]&&ac.last[ret] = =ac.root) -dp[i+1][ret] + = dp[i][j]*Por[k]; the } the } the DoubleAns =0;94 for(inti =0; I < AC. L i++) theAns + =Dp[l][i]; theprintf"Case #%d:%f\n", ca++, ans); the }98 return 0; About}
UVA 11468 "ac Automaton +DP"