P2622 关灯问题II 【状态压缩&bfs】

题目描述

现有n盏灯,以及m个按钮。每个按钮可以同时控制这n盏灯——按下了第i个按钮,对于所有的灯都有一个效果。按下i按钮对于第j盏灯,是下面3中效果之一:如果a[i][j]为1,那么当这盏灯开了的时候,把它关上,否则不管;如果为-1的话,如果这盏灯是关的,那么把它打开,否则也不管;如果是0,无论这灯是否开,都不管。

现在这些灯都是开的,给出所有开关对所有灯的控制效果,求问最少要按几下按钮才能全部关掉。
输入格式

前两行两个数,n m

接下来m行,每行n个数,a[i][j]表示第i个开关对第j个灯的效果。
输出格式

一个整数,表示最少按按钮次数。如果没有任何办法使其全部关闭,输出-1
输入输出样例
输入 #1

3
2
1 0 1
-1 1 0

输出 #1

2

说明/提示

对于20%数据,输出无解可以得分。

对于20%数据,n<=5

对于20%数据,m<=20

上面的数据点可能会重叠。

对于100%数据 n<=10,m<=100

#include <iostream>
#include <cstring>
#include <queue>
#include <algorithm>
#define mem(a, b) memset(a, b, sizeof(a))
using namespace std;

const int maxn = 1e3 + 10;
int a[maxn][maxn];
bool vis[maxn];
int n, m;

struct node{
	int dp, step;
};

void bfs() {
	queue<node>que;
	node cur;
	cur.dp = (1 << n) - 1;
	cur.step = 0;
	que.push(cur);
	vis[cur.dp] = true;
	while(!que.empty()) {
		cur = que.front();
		que.pop();
		node tem = cur;
		for(int i = 1; i <= m; i++) {
			tem = cur;
			int now = tem.dp;
			for(int j = 1; j <= n; j++) {
				if(a[i][j] == 1) {
					if( (1 << (j - 1)) & now)
						now = (1 << (j - 1)) ^ now;//,cout << now << endl;
				}
				else if(a[i][j] == -1)
					now = (1 << (j - 1)) | now;
			}
			if(vis[now] == true)
				continue;
			vis[now] = true;
			tem.dp = now;
			tem.step++;
			if(now == 0) {
				cout << tem.step << endl;
				return;
			}
			que.push(tem);
		}
	}
} 

int main() {
	cin >> n >> m;
	for(int i = 1; i <= m; i++) {
		for(int j = 1; j <= n; j++) {
			cin >> a[i][j];
		}
	}
	bfs();
	if(vis[0] == 0)
		cout << -1 << endl;
	return 0;
}
发布了78 篇原创文章 · 获赞 15 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/ln2037/article/details/104008097
今日推荐