lightoj 1092 Lighted Panels"/>
[状压dp] lightoj 1092 Lighted Panels
@(ACM题目)[字符串, kmp]
Description
You are given an R×C 2D grid consisting of several light panels. Each cell contains either a ‘*’ or a ‘.’ . ‘*’ means the panel is on, and ‘.’ means it’s off. If you touch a panel, its state will be toggled. That means, if you touch a panel that’s on, it will turn off, and if you touch a panel that’s off, it will turn on. But if we touch a panel, all its horizontal, vertical, and diagonal adjacent panels will also toggle their states.
Now you are given the configuration of the grid. Your goal is to turn on all the lights. Print the minimum number of touches required to achieve this goal.
Input
Input starts with an integer T(≤125) , denoting the number of test cases.
Each test case starts with two integers R(1≤R≤8) and C (1≤C≤8) . Then there will be R lines each containingC characters (‘*’ or ‘.’).
Output
For each test case, print the case number and the minimum number of touches required to have all the light panels in the board on at the same time. If it is not possible then print “impossible”.
Sample Input
4
5 5
*****
*…*
*…*
*…*
*****
1 2
.*
3 3
**.
**.
…
4 4
*…
**..
..**
…*
Sample Output
Case 1: 1
Case 2: impossible
Case 3: 2
Case 4: 10
题目分析
题意为给定由.
和*
组成的矩阵,求最少的操作数,使其全变成*
,其中一次操作为选择一个位置,将该位置以及8个与它相邻的位置反转。
由于行、列数都不超过8,可以用状压。
易知一个位置最多被按下一次。我们只需要枚举第一行和第一列的最终状态,对于每一种最终状态检查其是否合法即可。
代码
#include <iostream>
#include<cstdio>
#include<cmath>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 10;
const int inf = maxn*maxn+5;
const int d1[]={-1, -1, -1, +0, +0, +0, +1, +1, +1};
const int d2[]={-1, +0, +1, -1, +0, +1, -1, +0, +1};
int main()
{
// freopen("in.txt","r",stdin);int T;cin>>T;for(int tt=1;tt<=T;tt++){int m,n;cin>>m>>n;char ch;int ans=inf;int a[maxn][maxn]={0};int f[maxn][maxn]={0};for(int i=1;i<=m;i++)for(int j=1;j<=n;j++){scanf(" %c",&ch);if(ch=='.') a[i][j]=1;}int x,y,nx,ny;for(int s=0;s<(1<<(m+n-1));s++){for(int j=1;j<=n;j++) f[1][j]=(s>>(j-1))&1;for(int i=2;i<=m;i++) f[i][1]=(s>>(n+i-2))&1;for(int i=2;i<=m;i++)for(int j=2;j<=n;j++){x=i-1,y=j-1;f[i][j]=a[x][y];for(int k=0;k<8;k++){nx=x+d1[k],ny=y+d2[k];f[i][j]=f[i][j]^f[nx][ny];}}bool pd=true;int tmp;for(int i=1;i<=m;i++){x=i;y=n;tmp=a[i][n];for(int k=0;k<9;k++){nx=x+d1[k],ny=y+d2[k];tmp=tmp^f[nx][ny];}if(tmp!=0){pd=false;break;}}for(int j=1;j<=n;j++){x=m;y=j;tmp=a[m][j];for(int k=0;k<9;k++){nx=x+d1[k],ny=y+d2[k];tmp=tmp^f[nx][ny];}if(tmp!=0){pd=false;break;}}if(pd){int tans=0;for(int i=1;i<=m;i++)for(int j=1;j<=n;j++) tans+=f[i][j];if(tans<ans) ans=tans;}}if(ans!=inf) printf("Case %d: %d\n",tt,ans);else printf("Case %d: impossible\n",tt);}return 0;
}
更多推荐
[状压dp] lightoj 1092 Lighted Panels
发布评论