poj2965(枚举)题解
题目
Description
The game “The Pilots Brothers: following the stripy elephant” has a quest where a player needs to open a refrigerator.
There are 16 handles on the refrigerator door. Every handle can be in one of two states: open or closed. The refrigerator is open only when all handles are open. The handles are represented as a matrix 4х4. You can change the state of a handle in any location [i, j] (1 ≤ i, j ≤ 4). However, this also changes states of all handles in row i and all handles in column j.
The task is to determine the minimum number of handle switching necessary to open the refrigerator.
Input
The input contains four lines. Each of the four lines contains four characters describing the initial state of appropriate handles. A symbol “+” means that the handle is in closed state, whereas the symbol “−” means “open”. At least one of the handles is initially closed.
Output
The first line of the input contains N – the minimum number of switching. The rest N lines describe switching sequence. Each of the lines contains a row number and a column number of the matrix separated by one or more spaces. If there are several solutions, you may give any one of them.
Sample Input
-±-
-±-
Sample Output
6
1 1
1 3
1 4
4 1
4 3
4 4
题意
要求:输入4行4列的字符(只包含“+”和“-”),将字符全改为"-";
改变规则:改变一个点:这个点的行和列都要改变;
改变方式:"+"=>"-", “-”=>"+"
解题思路
枚举每一种情况,找到一种满足要求的情况即可;用一个数组保存每种情况下选择的点;当找到满足情况时,将当前数组保存到另一数组中;
最后输出满足情况有多少点,并且输出点的顺序(保存到另一数组中的点);
#include<cstdio>
#include <iostream>
#include<cmath>
#include<cstring>
using namespace std;
char a[5][5];
int b[50];
int c[50];
int mm=100;
bool all=false;
bool pan()
{
for(int i=1;i<=4;i++)
for(int j=1;j<=4;j++)
if(a[i][j]!='-')
return false;
return true;
}
void bian(int x,int y,int z)
{
for(int i=1;i<=4;i++) //改变行和列的点
{
if(a[x][i]=='-')
a[x][i]='+';
else
a[x][i]='-';
if(a[i][y]=='-')
a[i][y]='+';
else
a[i][y]='-';
}
if(a[x][y]=='-') //因为改变行和列 (x,y)这个点改变了两次 所以重新改变一次
a[x][y]='+';
else
a[x][y]='-';
if(z!=0) 保存选择的点
b[z*2-1]=x;
b[z*2]=y;
}
void meiju(int n,int m,int num)
{
if(all)
return ;
for(int i=1;i<=4;i++)
{
for(int j=1;j<=4;j++)
{
if(i<n||(i==n&&j<=m))
continue;
bian(i,j,num); //改变
if(pan())
{
mm=num;
for(int l=1;l<=2*mm;l++)
c[l]=b[l];
all=true;
return ;
}
meiju(i,j,num+1);
bian(i,j,0); //还原 b数组不需要还原,因为下一次改变时会覆盖,所以没必要还原
}
}
}
int main()
{
for(int i=1;i<=4;i++)
for(int j=1;j<=4;j++)
cin>>a[i][j];
if(pan())
{
cout<<'0'<<endl;
}
else
{
meiju(0,0,1);
cout<<mm<<endl;
for(int i=1;i<=mm;i++)
cout<<c[i*2-1]<<" "<<c[i*2]<<endl;
}
return 0;
}