题意:给出N(N<=10)个字符串(length<=10),定义两个串a,b之间的公共序列长度为
将a,b对齐后,相同位置上相同字母的个数,a,b的最长公共序列长度自然是相同字母数的
最大值,如a='abcd',b='bed',a,b的最长公共序列长度为2.
如要求将N个字符串排列,使得相邻的N-1对字符串的最长公共序列长度和最大.
(出题人不负责,N怎么也应该有20,这题暴搜可以过.)
讲讲状压的做法.
f[i,j]中j(二进制)表示哪些字符串已选,i表示最右边的是哪一个字符串.
转移时,枚举j中的一个不为0的位,去掉,成为j',i'表示j'中所有不为0的位,
则f[i,j]=max{f[i',j']+LCS(s[i],s[i'])} ((j'>>(i'-1))&1=1)
(LCS是上面定义的那种).
ans=max{f[i,1<<n-1]} (1<=i<=n)
code:
type stringx=string[11];
var f:array[0..11,0..1100] of longint;g:array[0..11,0..11] of longint;s:array[0..11] of stringx;n,i,j,opt,now,ans:longint;function max(a,b:longint):longint;beginif a>b then exit(a); exit(b);end;function work(a,b:stringx):longint;var p,q,la,lb,l,c,maxl:longint;beginmaxl:=0;la:=length(a);lb:=length(b);for p:=1 to la dofor q:=1 to lb dobeginl:=0;c:=0;while (p+l<=la)and(q+l<=lb) dobeginif a[p+l]=b[q+l] then inc(c);inc(l);end;if c>maxl then maxl:=c;end;exit(maxl);end;function check(num:longint):boolean;var c:longint;beginc:=0;while num>0 dobegininc(c,num and 1);num:=num>>1;end;exit(c>1);end;beginwhile not seekeof dobeginreadln(n);if n<=0 then break;for i:=1 to n do readln(s[i]);for i:=1 to n-1 dofor j:=i+1 to n dobeging[i,j]:=work(s[i],s[j]);g[j,i]:=g[i,j];end;fillchar(f,sizeof(f),171);for i:=1 to n do f[i,1<<(i-1)]:=0;for opt:=1 to 1<<n-1 doif check(opt) thenfor i:=1 to n doif (opt>>(i-1)) and 1=1 thenbeginnow:=opt xor (1<<(i-1));for j:=1 to n doif (now>>(j-1)) and 1=1 thenf[i,opt]:=max(f[i,opt],f[j,now]+g[j,i]);end;ans:=0;for i:=1 to n doans:=max(ans,f[i,1<<n-1]);writeln(ans);end;
end.
note:求最大权哈密顿回路可以用状态压缩的方法,类似此题.
另外一些摆放类的问题求最值也可以用状压(以后会写).