132. Another Chocolate Maniac time limit per test: 0.25 sec. memory limit per test: 4096 KB Bob really LOVES chocolate. He thinks he never gets enough. Imagine his joy when his parents told him that they would buy him many rectangular chocolate pieces for his birthday. A piece of chocolate is a 2x1 or 1x2 rectangle.
Input The first line of the input contains 2 integers: M (1<=M<=70) and N (1<=N<=7). Next, M lines will follow, each of them containing N characters,
Output You should output one integer: the minimal amount of pieces of chocolate which need to be placed on the cake. Sample Input 5 5 .*..* *.... ..**. **.*. .**.. Sample Output 4 |
思路 :dp[ i ][ s1 ][ s2 ] 表示第 i -1 行状态为s2,第 i 行状态为s2的方案数。然后就是dfs枚举状态。
dfs(p , s1 , s2 , s3 , cnt )(假设当前枚举的是第 i 行)p为当前枚举的列号 ,s1为i-2行的状态 ,
s2为i-1的状态,s3为i行的状态,cnt为放置的数目。
#include <iostream> #include <cstdio> #include <cstring> using namespace std; const int B[8]= {1,2,4,8,16,32,64,128}; const int inf=1<<30; const int maxn=1<<8; const int N=75; int dp[2][maxn][maxn],a[N],cur,len,n,m,tmp,now; char ch[10]; void input() { scanf("%d %d",&n,&m); for(int i=1; i<=n; i++) { scanf("%s",ch); for(int j=0; j<m; j++) { a[i]<<=1; if(ch[j]=='*') a[i]+=1; } } } void initial() { cur=0; len=1<<m; for(int i=0; i<2; i++) for(int j=0; j<maxn; j++) for(int k=0; k<maxn; k++) dp[i][j][k]=inf; dp[cur][len-1][a[1]]=0; } void dfs(int p,int s1,int s2,int s3,int cnt) { if(p>0 && !(s1 & B[p-1]) && !(s2 & B[p-1])) return ; if(p>1 && !(s2 & B[p-1]) && !(s2 & B[p-2])) return ; if(p>=m) { dp[cur][s2][s3]=min(dp[cur][s2][s3],dp[cur^1][tmp][now]+cnt); return ; } dfs(p+1,s1,s2,s3,cnt); if(p<m-1 && !(s2 & B[p]) && !(s2 & B[p+1])) dfs(p+1,s1,s2|B[p]|B[p+1],s3,cnt+1); if(!(s2 & B[p]) && !(s3 & B[p])) dfs(p+1,s1,s2|B[p],s3|B[p],cnt+1); } void solve() { for(int i=1; i<=n; i++) { cur^=1; for(int j=0; j<len; j++) for(int k=0; k<len; k++) if(dp[cur^1][j][k]<inf) { tmp=j; now=k; dfs(0,j,k,a[i+1],0); } for(int j=0; j<len; j++) for(int k=0; k<len; k++) dp[cur^1][j][k]=inf; } int ans=inf; for(int i=0; i<len; i++) ans=min(ans,dp[cur][i][0]); printf("%d\n",ans); } int main() { input(); initial(); solve(); return 0; }