Input
2 1
xt
tx
Output
2
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define N 210
#define L 100100
#define base 131
using namespace std;
typedef long long ll;
ll n,m;
unsigned long long hash[N][L],pow[L];
ll f[35][N][N];
ll ans[N][N];
ll change[N][N];
int len[N];
char s[L];
ll getlen(int x,int y)
{
int lll;
if(x==y)lll=len[x]-1;
else lll=min(len[x],len[y]);
for(int i=lll;i>=0;i--)
if(hash[x][len[x]]-hash[x][len[x]-i]*pow[i]==hash[y][i])
return len[y]-i;
}
int main()
{
scanf("%lld%lld",&n,&m);
m--;
pow[0]=1;
for(int i=1;i<L;i++)pow[i]=pow[i-1]*base;
int minl=0x3f3f3f3f;
for(int i=1;i<=n;i++)
{
scanf("%s",s+1);
len[i]=strlen(s+1);
minl=min(minl,len[i]);
for(int j=1;j<=len[i];j++)
{
hash[i][j]=hash[i][j-1]*base+s[j];
}
}
if(m==0){printf("%d\n",minl);return 0;}
memset(f,0x3f,sizeof(f));
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
f[0][i][j]=getlen(i,j);
for(ll lll=1;(1ll<<lll)<=m;lll++)
for(int k=1;k<=n;k++)
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
f[lll][i][j]=min(f[lll][i][j],f[lll-1][i][k]+f[lll-1][k][j]);
int tmp_the_smallest;
for(ll i=0;(1ll<<i)<=m;i++)if(m&(1ll<<i)){tmp_the_smallest=i;break;}
memcpy(ans,f[tmp_the_smallest],sizeof(ans));
for(ll lll=tmp_the_smallest+1;(1ll<<lll)<=m;lll++)
{
if(m&(1ll<<lll))
{
memset(change,0x3f,sizeof(change));
for(int k=1;k<=n;k++)
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
change[i][j]=min(change[i][j],min(ans[i][k]+f[lll][k][j],f[lll][i][k]+ans[k][j]));
memcpy(ans,change,sizeof(ans));
}
}
ll lenl=0x3f3f3f3f3f3f3f3fll;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
lenl=min(lenl,len[i]+ans[i][j]);
printf("%lld\n",lenl);
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
BZOJ 2085 [Poi2010]Hamsters Hash+倍增floyd
原文地址:http://blog.csdn.net/wzq_qwq/article/details/48139059