[UVA11468] Substring && AC自动机

来源:互联网 发布:arp static ip mac 编辑:程序博客网 时间:2024/05/16 23:55

用全概率公式计算 把是单词的地方标记一下就行 

#include<cstdio>#include<algorithm>#include<cstring>#include<iostream>#include<queue>#include<map>#define SF scanf#define PF printf#define max(a, b) ((a) < (b) ? (b) : (a))using namespace std;typedef long long LL;const int MAXN = 500;const int MAXL = 500;const int SZ = 62;char s[50+10];double p[SZ+10];inline int ID(char c) {if('0' <= c && c <= '9') return c - '0';if('a' <= c && c <= 'z') return c - 'a' + 10;if('A' <= c && c <= 'Z') return c - 'A' + 36;}struct Aho_Corasick{int ch[MAXL+10][SZ], Ncnt, match[MAXL+10];bool vis[MAXL+10][MAXN+10];double d[MAXL+10][MAXL+10];int f[MAXL+10];void init() { memset(ch[0], 0, sizeof(ch[0])); Ncnt = 1;memset(vis, 0, sizeof(vis));}void New() {memset(ch[Ncnt], 0, sizeof(ch[Ncnt]));match[Ncnt] = 0;}void insert(char *s, int v){int u = 0, n = strlen(s);for(int i = 0; i < n; i++){int c = ID(s[i]);if(!ch[u][c]) {New();ch[u][c] = Ncnt++;printf("** %d  %d %d\n", u, c, Ncnt);}u = ch[u][c];}match[u] = 1;}void getFail(){queue <int> q;f[0] = 0;for(int c = 0; c < SZ; c++){int u = ch[0][c];if(u) { f[u] = 0; q.push(u);}}while(!q.empty()){int r = q.front(); q.pop();for(int c = 0; c < SZ; c++){int u = ch[r][c];if(!u) { ch[r][c] = ch[f[r]][c]; continue; }q.push(u);int v = f[r];while(v && !ch[v][c]) v = f[v];f[u] = ch[v][c];match[u] |= match[f[u]];}}}double getProb(int u, int L) {if(!L) return 1.0;if(vis[u][L]) return d[u][L];vis[u][L] = 1;double &ans = d[u][L];ans = 0.0;for(int i = 0; i < SZ; i++) if(p[i] && !match[ch[u][i]]) ans += p[i] * getProb(ch[u][i], L-1);return ans;}}ac;int main(){int kase = 0;int T; SF("%d", &T); while(T--) {ac.init();memset(p, 0, sizeof(p));int K, L, n; SF("%d", &K);for(int i = 1; i <= K; i++) { SF("%s", s); ac.insert(s, i); }ac.getFail();SF("%d", &n);for(int i = 1; i <= n; i++){SF("%s", s);int c = ID(s[0]);SF("%lf", &p[c]);}SF("%d", &L);PF("Case #%d: %.6lf\n", ++kase, ac.getProb(0, L));}}


0 0
原创粉丝点击