bzoj4044: [Cerc2014] Virus synthesis(迴文自動機)
阿新 • • 發佈:2018-12-31
#include<bits/stdc++.h>
using namespace std;
const int N=100002;
int mp[99],ans,T,f[N],fail[N],ch[N][4],sz,q[N],h,t,len[N],s[N],n,las[N],last,u,v,i;
char c;
void init(int u,int l,int f){
ch[u][0]=ch[u][1]=ch[u][2]=ch[u][3]=0;
len[u]=l,fail[u]=f;
}
int F(int u){for (;s[n-len[u]-1 ]!=s[n];u=fail[u]);return u;}
void extend(int c){
int u=F(last);
if (!ch[u][c]){
int v=++sz;
init(ch[u][c]=v,len[u]+2,ch[F(fail[u])][c]);
if (len[v]<=2) las[v]=fail[v];
else{
int x=las[u];
for (;s[n-len[x]-1]!=s[n] || (len[x]+2<<1)>len[v];x=fail[x]);
las[v]=ch[x][c];
}
}
last=ch[u][c];
}
void build(){
last=n=0,sz=1;
for (;c<'A' || c>'Z';c=getchar());
for (;'A'<=c && c<='Z';c=getchar()) extend(s[++n]=mp[c]);
}
int main(){
mp['C']=1,mp['G']=2,mp['T']=3;s[0]=-1;
for (scanf("%d",&T);T--;){
init(0,0,1),init(1,-1,0);
f[0]=fail[0]=1,fail[1]=0;
build();
for (i=1;i<=sz;i++)
if (len[i]&1) f[i]=len[i];
h=0,t=1,ans=n;
while (h<t){
u=q[h++];
for (i=0;i<4;i++)
if (v=ch[u][i]){
f[v]=min(f[u]+1,len[v]/2+1+f[las[v]]-len[las[v]]);
ans=min(ans,n+f[v]-len[v]);
q[t++]=v;
}
}
printf("%d\n",ans);
}
}