算法复习——状压dp
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法复习——状压dp相关的知识,希望对你有一定的参考价值。
状压dp的核心在于,当我们不能通过表现单一的对象的状态来达到dp的最优子结构和无后效性原则时,我们可能保存多个元素的有关信息··这时候利用2进制的01来表示每个元素相关状态并将其压缩成2进制数就可以达到目的····此时熟悉相关的位运算就很重要了····以下是常见的一些需要位运算方法
然后说实话状压dp其它方面就和普通dp差不多了···它不像数位区间树形那样或多或少好歹有自己一定套路或规律····如何想到转移方程和状态也就成了其最难的地方···
例题:
1.Corn Fields(poj3254)
Description
Farmer John has purchased a lush new rectangular pasture composed of M by N (1 ≤ M ≤ 12; 1 ≤ N ≤ 12) square parcels. He wants to grow some yummy corn for the cows on a number of squares. Regrettably, some of the squares are infertile and can‘t be planted. Canny FJ knows that the cows dislike eating close to each other, so when choosing which squares to plant, he avoids choosing squares that are adjacent; no two chosen squares share an edge. He has not yet made the final choice as to which squares to plant.
Being a very open-minded man, Farmer John wants to consider all possible options for how to choose the squares for planting. He is so open-minded that he considers choosing no squares as a valid option! Please help Farmer John determine the number of ways he can choose the squares to plant.
Input
Lines 2..M+1: Line i+1 describes row i of the pasture with N space-separated integers indicating whether a square is fertile (1 for fertile, 0 for infertile)
Output
Sample Input
2 3 1 1 1 0 1 0
Sample Output
9
Hint
1 2 3
4
There are four ways to plant only on one squares (1, 2, 3, or 4), three ways to plant on two squares (13, 14, or 34), 1 way to plant on three squares (134), and one way to plant on no squares. 4+3+1+1=9.
#include<iostream> #include<cstdio> #include<cstdlib> #include<cmath> #include<ctime> #include<cctype> #include<cstring> #include<string> #include<algorithm> using namespace std; const int N=15; const int mod=1e+8; int f[N][5000],map[N],n,m,ans,maxx; inline int R() { char c;int f=0; for(c=getchar();c<‘0‘||c>‘9‘;c=getchar()); for(;c<=‘9‘&&c>=‘0‘;c=getchar()) f=(f<<3)+(f<<1)+c-‘0‘; return f; } inline void solve() { for(int i=0;i<maxx;i++) if(((i|map[1])==map[1])&&!(i&(i>>1))) f[1][i]=1; for(int i=2;i<=n;i++) for(int j=0;j<maxx;j++) if(f[i-1][j]) for(int k=0;k<maxx;k++) if(((k|map[i])==map[i])&&!(k&(k>>1))&&!(k&j)) f[i][k]=(f[i][k]+f[i-1][j])%mod; for(int i=0;i<maxx;i++) ans=(ans+f[n][i])%mod; } int main() { //freopen("a.in","r",stdin); n=R(),m=R();int a;maxx=(1<<m); for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) { a=R(); if(a) map[i]|=(1<<(j-1)); } solve(); cout<<ans<<endl; return 0; }
以上是关于算法复习——状压dp的主要内容,如果未能解决你的问题,请参考以下文章
18.06.03 POJ 4126:DNA 15年程设期末05(状压DP)