标签:bzoj2085 poi2010 hamsters ac自动机 倍增floyd
#include <stdio.h>
int main()
{
puts("转载请注明出处[vmurder]谢谢");
puts("网址:blog.csdn.net/vmurder/article/details/45747235");
}
首先我们搞个
然后把每个串当成一个点,倍增
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define N 101000
#define M 205
#define T 26
#define inf 0x3f3f3f3f
#define INF 0x3f3f3f3f3f3f3f3fll
using namespace std;
long long f[M][M],g[M][M],map[M][M];
int n,m;
int dist[N],pos[M],len[M];
struct Eli
{
char src[N];
int son[N][T],cnt;
int insert(int id)
{
scanf("%s",src);
len[id]=strlen(src);
int i,x=0,alp;
for(i=0;src[i];i++)
{
alp=src[i]-‘a‘;
if(!son[x][alp])son[x][alp]=++cnt;
x=son[x][alp];
}
return x;
}
int fail[N];
queue<int>q;
void keep()
{
int i,u,v;
q.push(0);
while(!q.empty())
{
u=q.front(),q.pop();
for(i=0;i<T;i++)
{
if(v=son[u][i])
{
if(u==0)fail[v]=0;
else fail[v]=son[fail[u]][i];
q.push(v);
}
else son[u][i]=son[fail[u]][i];
}
}
}
int vis[N],dist[N];
void bfs(int s)
{
int i,u,v;
q.push(s),dist[s]=0;
while(!q.empty())
{
u=q.front(),q.pop();
for(i=0;i<T;i++)
{
v=son[u][i];
if(vis[v]!=s)
{
vis[v]=s;
dist[v]=dist[u]+1;
q.push(v);
}
}
}
}
void deal(int s)
{
int i,j,k;
for(i=1;i<=n;i++)
map[s][i]=dist[pos[i]];
}
}eli;
void deal_the_name()
{
int i,j,k;
for(i=1;i<=n;i++)
pos[i]=eli.insert(i);
eli.keep();
for(i=1;i<=n;i++)
{
eli.bfs(pos[i]);
eli.deal(i);
}
}
void power(int n,int m)
{
int i,j,k;
memset(f,0x3f,sizeof f);
for(i=1;i<=n;i++)f[i][i]=0;
while(m)
{
if(m&1)
{
memset(g,0x3f,sizeof g);
for(k=1;k<=n;k++)for(i=1;i<=n;i++)for(j=1;j<=n;j++)g[i][j]=min(g[i][j],f[i][k]+map[k][j]);
for(i=1;i<=n;i++)for(j=1;j<=n;j++)f[i][j]=g[i][j];
}
memset(g,0x3f,sizeof g);
for(k=1;k<=n;k++)for(i=1;i<=n;i++)for(j=1;j<=n;j++)g[i][j]=min(g[i][j],map[i][k]+map[k][j]);
for(i=1;i<=n;i++)for(j=1;j<=n;j++)map[i][j]=g[i][j];
m>>=1;
}
}
int main()
{
int i,j,k;
int a,b,c;
scanf("%d%d",&n,&m);
deal_the_name();
power(n,m-1);
long long ans=INF;
for(i=1;i<=n;i++)for(j=1;j<=n;j++)
ans=min(ans,f[i][j]+len[i]);
cout<<ans<<endl;
return 0;
}
【BZOJ2085】【Poi2010】Hamsters AC自动机bfs+倍增floyd
标签:bzoj2085 poi2010 hamsters ac自动机 倍增floyd
原文地址:http://blog.csdn.net/vmurder/article/details/45747235