题目传送门:http://www.lydsy.com/JudgeOnline/problem.php?id=1444
题目分析:首先考虑静态的问题:如果已经生成一个字符串,如何让它跟所有模式串匹配?答案是建出所有模式串的AC自动机,然后让生成串在上面跑,如果跑到某个有endpos的节点就一直停在那里。
然后考虑动态的问题:如果生成串无限长,如何求出它停在每个节点的概率?把AC自动机扩展成Trie图,并设f[i]表示匹配时停在i的概率,则有:
手算一下第一组样例,发现f[root]解不出来?没关系,我们只需要知道每一个有endpos的节点,f值的相对比例关系就行了。所以f[root]随便设为1(后来我发现这样设的话有endpos的节点,f值之和也是1)。
为了确保正确性,我在写code之前还手算了第二组样例,解了一个八元的线性方程组,结果算了半个小时还算错了。最后发现是我一开始AC机建错了,前功尽弃QAQ。用了1h终于算出来了,然后我码code只用了35min……以后太大的样例绝不能手算啊啊啊啊啊!
注意有些字符造不出来,可能导致所有人的获胜概率均为0,要特判。eps开到1e-8最好,开大了会WA。
CODE:
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
const int maxn=200;
const int maxm=15;
const double eps=1e-8;
struct Tnode
{
int endpos;
Tnode *son[maxm],*fsto;
} tree[maxn];
Tnode *Root;
int cur=0;
Tnode *que[maxn];
int head=0,tail=1;
double a[maxn][maxn];
double f[maxn];
double p[maxm];
char s[maxm];
int n,l,m;
Tnode *New_node()
{
cur++;
tree[cur].endpos=0;
tree[cur].fsto=NULL;
for (int i=0; ireturn tree+cur;
}
void Insert(int x)
{
Tnode *P=Root;
for (int j=0; jint to=s[j]-'A';
if (!P->son[to]) P->son[to]=New_node();
P=P->son[to];
}
P->endpos=x;
}
void Bfs()
{
que[1]=Root;
while (headfor (int i=0; ison[i];
if (P)
{
Tnode *Node=F->fsto;
while ( Node && !Node->son[i] ) Node=Node->fsto;
if (Node) P->fsto=Node->son[i];
else P->fsto=Root;
que[++tail]=P;
}
}
}
for (int i=0; iif (!Root->son[i]) Root->son[i]=Root;
for (int i=1; i<=tail; i++)
{
Tnode *P=que[i];
for (int j=0; jif (!P->son[j]) P->son[j]=P->fsto->son[j];
}
}
double Abs(double x)
{
if (x>=0.0) return x;
return -x;
}
int Gauss()
{
int R,r=1,c=1;
while ( r<=cur && c<=cur )
{
R=r;
for (int i=r+1; i<=cur; i++)
if ( Abs(a[i][c])>Abs(a[R][c]) ) R=i;
if ( Abs(a[R][c])<=eps ) r--;
else
{
for (int i=c; i<=cur+1; i++) swap(a[r][i],a[R][i]);
for (int i=r+1; i<=cur; i++)
if ( Abs(a[i][c])>eps )
{
for (int j=c+1; j<=cur+1; j++)
a[i][j]=a[i][j]/a[i][c]-a[r][j]/a[r][c];
a[i][c]=0.0;
}
}
r++;
c++;
}
for (int i=r; i<=cur; i++)
if ( Abs(a[i][cur+1])>eps ) return -1;
if (r<=n) return n-r+1;
for (int i=cur; i>=1; i--)
{
for (int j=i+1; j<=cur; j++)
a[i][cur+1]-=(a[i][j]*a[j][cur+1]);
a[i][cur+1]/=a[i][i];
}
}
int main()
{
freopen("1444.in","r",stdin);
freopen("1444.out","w",stdout);
scanf("%d%d%d",&n,&l,&m);
int hs=0;
for (int i=0; iint x,y;
scanf("%d%d",&x,&y);
p[i]=(double)x/(double)y;
if (p[i]>eps) hs|=(1<bool sol=false;
Root=New_node();
for (int i=1; i<=n; i++)
{
scanf("%s",s);
Insert(i);
int now=0;
for (int j=0; j1<<(s[j]-'A'));
if ((now&hs)==now) sol=true;
}
Bfs();
if (!sol)
{
for (int i=1; i<=n; i++) printf("0.00\n");
return 0;
}
for (int i=1; i<=cur; i++) if (!tree[i].endpos)
for (int c=0; cint j=(tree[i].son[c]-tree);
a[j][i]+=p[c];
}
for (int i=1; i<=cur; i++) a[i][i]-=1.0;
a[1][cur+1]=-1.0;
Gauss();
for (int i=1; i<=cur; i++)
if (tree[i].endpos) f[ tree[i].endpos ]=a[i][cur+1];
for (int i=1; i<=n; i++) printf("%.2lf\n",f[i]+eps);
return 0;
}