状压动规_(POJ2817)
生活随笔
收集整理的這篇文章主要介紹了
状压动规_(POJ2817)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題意:給出N(N<=10)個字符串(length<=10),定義兩個串a(chǎn),b之間的公共序列長度為
將a,b對齊后,相同位置上相同字母的個數(shù),a,b的最長公共序列長度自然是相同字母數(shù)的
最大值,如a='abcd',b='bed',a,b的最長公共序列長度為2.
如要求將N個字符串排列,使得相鄰的N-1對字符串的最長公共序列長度和最大.
(出題人不負(fù)責(zé),N怎么也應(yīng)該有20,這題暴搜可以過.)
講講狀壓的做法.
f[i,j]中j(二進(jìn)制)表示哪些字符串已選,i表示最右邊的是哪一個字符串.
轉(zhuǎn)移時,枚舉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:求最大權(quán)哈密頓回路可以用狀態(tài)壓縮的方法,類似此題.
另外一些擺放類的問題求最值也可以用狀壓(以后會寫).
轉(zhuǎn)載于:https://www.cnblogs.com/exponent/archive/2011/08/07/2130146.html
總結(jié)
以上是生活随笔為你收集整理的状压动规_(POJ2817)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 面向Web应用的并发压力测试工具——Lo
- 下一篇: 如何查看数据文件或者Log文件是否增长过