Title Description
N conventional lamps, and m buttons. Each button can simultaneously control the lamp n - i-button is pressed, all lamps have an effect. For the first pressed i j lamp, is one of the 3 following effects: If A [i] [j] is 1, then when this lamp when opened, shut it off, otherwise no matter; If -1 then, if this lamp is off, then open it, otherwise no matter; if it is 0, regardless of whether these lights on, do not care.
Now these lights are open, given all the switches to control the effect of all the lamps, inquire at least a few Yaoan button to switch off all.
Input Format
The first two rows of two numbers, nm
Subsequently m rows, each row number n, a [i] [j] indicates the effect of the i-th switch of j-th light.
Output Format
An integer representing the minimum number press the button. If there is no way to make it all off, output -1
Input # 1
3
2
1 0 1
-1 1 0
Output # 1
2
Problem-solving ideas:
This problem can be searched first thought, bfs, enumeration affect the n switches for each state.
Then for this question in a state, it is known, each point only two states, i.e., on or off, then we can use the number of binary bits to represent a light switch, that is to say for the i th light, if the i the number of positions is then i say this lamp is open, otherwise closed.
A state of the modifier may also be used if the nature of the bit operation, bit i of a number of modifications.
So write good code, then dfs indicates the status binary search, the search is on to explain the state found a solution 0:00.
In fact, that is the state of compression, it is no compression ah, nothing more than a status value represents a binary number. That white is simple violence.
AC Code:
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 1e6 +10;
struct node {
int sta,step;
node(int a,int b)
{
sta = a;
step = b;
}
};
int a[105][105];
int n,m;
bool mark[1<<11];
int bfs()
{
int sta = 1;
for(int i = 1 ; i < m ; i ++)
{
sta |= 1<<i;
}
memset(mark,0,sizeof(mark));
queue<node> que;
que.push(node(sta,0));
while(!que.empty())
{
node tmp = que.front();
que.pop();
if(tmp.sta == 0)
return tmp.step;
for(int i = 0 ; i < n ; i ++)
{
int tmp1 = tmp.sta;
for(int j = 0 ; j < m ; j ++)
{
if(a[i][j] == 1 && (tmp.sta&(1<<j)))
tmp1 = tmp1^(1<<j);
if(a[i][j] == -1)
tmp1 = tmp1|(1<<j);
}
if(!mark[tmp1])
que.push(node(tmp1,tmp.step+1));
mark[tmp1] = true;
}
}
return -1;
}
signed main()
{
cin>>m>>n;
for(int i = 0 ; i < n ; i ++)
for(int j = 0 ; j < m ; j ++)
cin>>a[i][j];
cout<<bfs()<<endl;
}