Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 391 Accepted Submission(s): 109
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <queue> 5 #include <algorithm> 6 #include <cmath> 7 using namespace std; 8 9 const int N=250; 10 const int SZ=26; 11 const double eps=1e-8; 12 double p[27],A[N][N]; 13 bool inf[N]; 14 struct AC 15 { 16 int ch[N][26]; 17 int sz,val[N],fail[N]; 18 void init(){ 19 sz=1;memset(val,0,sizeof(val)); 20 memset(ch[0],0,sizeof(ch[0])); 21 } 22 void insert(char *s) 23 { 24 int rt=0; 25 for (int i=0;s[i];i++){ 26 int c=s[i]-‘a‘; 27 if (ch[rt][c]==0){ 28 ch[rt][c]=sz; 29 memset(ch[sz],0,sizeof(ch[sz])); 30 sz++; 31 } 32 rt=ch[rt][c]; 33 } 34 val[rt]=1; 35 } 36 void getfail() 37 { 38 queue<int>q; 39 for (int i=0;i<SZ;i++) 40 { 41 int c=ch[0][i]; 42 if (c){ q.push(c);fail[c]=0; } 43 } 44 while (!q.empty()) 45 { 46 int u=q.front();q.pop(); 47 for (int i=0;i<SZ;i++) 48 { 49 int c=ch[u][i]; 50 if (!c){ 51 ch[u][i]=ch[fail[u]][i]; 52 }else 53 { 54 int v=fail[u]; 55 q.push(c); 56 fail[c]=ch[v][i]; 57 val[c]|=val[fail[c]]; 58 } 59 } 60 } 61 } 62 }ac; 63 64 void build_matrix() 65 { 66 int i,j; 67 memset(A,0,sizeof(A)); 68 for(i=0;i<ac.sz;i++) 69 { 70 if(ac.val[i]){A[i][i]=1;A[i][ac.sz]=0;} 71 else 72 { 73 for(j=0;j<SZ;j++){int v=ac.ch[i][j];A[i][v]+=p[j];} 74 A[i][i]+=-1;A[i][ac.sz]=-1; 75 } 76 } 77 } 78 79 void gauss(int n) 80 { 81 int i,j,k,r; 82 for(i=0;i<n;i++) 83 { 84 r=i; 85 for(j=i+1;j<n;j++) 86 if(fabs(A[j][i])>fabs(A[r][i])) r=j; 87 if(fabs(A[r][i])<eps) continue; 88 if(r!=i) for(j=0;j<=n;j++) swap(A[r][j],A[i][j]); 89 for(k=0;k<n;k++) if(k!=i) 90 for(j=n;j>=i;j--) A[k][j]-=A[k][i]/A[i][i]*A[i][j]; 91 } 92 memset(inf,0,sizeof(inf)); 93 for(i=ac.sz-1;i>=0;i--){ 94 if(fabs(A[i][i])<eps&&fabs(A[i][ac.sz])>eps) inf[i]=1; 95 for(j=i+1;j<ac.sz;j++) 96 if(fabs(A[i][j])>eps&&inf[j]) inf[i]=1; 97 } 98 if(inf[0]) printf("Infinity\n"); 99 else printf("%.6lf\n",A[0][ac.sz]/A[0][0]+eps); 100 } 101 102 int main() 103 { 104 //freopen("b.txt","w",stdout); 105 int n,i,j;char s[20]; 106 while(~scanf("%d",&n)) 107 { 108 ac.init(); 109 for(i=0;i<SZ;i++) scanf("%lf",p+i); 110 for(i=0;i<n;i++) 111 { 112 scanf("%s",s);ac.insert(s); 113 } 114 ac.getfail(); 115 build_matrix(); 116 gauss(ac.sz); 117 } 118 return 0; 119 }
hdu 3992 AC自动机上的高斯消元求期望,布布扣,bubuko.com
原文:http://www.cnblogs.com/xiong-/p/3915538.html