BZOJ2085 : [Poi2010]Hamsters

时间:2023-03-10 02:51:29
BZOJ2085 : [Poi2010]Hamsters

设g[i][j]为i串至少加上几个字符后才能包含j,可以通过Hash求出。

然后就是求经过m-1条边的最短路,用倍增加速Floyed即可,时间复杂度$O(n^3\log m)$。

#include<cstdio>
#include<cstring>
#define rep(i,n) for(int i=0;i<n;i++)
typedef long long ll;
typedef unsigned int U;
const int N=200,M=100010,P=31;
const ll inf=1LL<<60;
int n,m,i,j,st[N],en[N],len[N],t=1,flag;U pow[M],f[M];char s[M],a[M];ll ans=inf;
inline U hash(int l,int r){return f[r]-f[l-1]*pow[r-l+1];}
inline int cal(int x,int y){
for(int i=(len[x]<len[y]?len[x]:len[y])-1;i;i--)if(hash(en[x]-i+1,en[x])==hash(st[y],st[y]+i-1))return i;
return 0;
}
inline void up(ll&a,ll b){if(a>b)a=b;}
struct mat{
ll a[N][N];
mat(){}
inline mat operator*(mat b){
mat c;
rep(i,n)rep(j,n)c.a[i][j]=inf;
rep(k,n)rep(i,n)rep(j,n)up(c.a[i][j],a[i][k]+b.a[k][j]);
return c;
}
}G,B;
int main(){
scanf("%d%d",&n,&m);
rep(i,n){
scanf("%s",s);
st[i]=t,len[i]=std::strlen(s);
rep(j,len[i])a[t+j]=s[j];
en[i]=t+len[i]-1,t+=len[i];
}
for(pow[0]=i=1;i<t;i++)pow[i]=pow[i-1]*P;
for(i=1;i<t;i++)f[i]=f[i-1]*P+a[i];
rep(i,n)rep(j,n)G.a[i][j]=len[j]-cal(i,j),B.a[i][j]=0;
for(m--;m;m>>=1,G=G*G)if(m&1){if(!flag)B=G,flag=1;else B=B*G;}
rep(i,n)rep(j,n)up(ans,B.a[i][j]+len[i]);
return printf("%lld",ans),0;
}