P2622 關燈問題II(狀壓dp)

題目鏈接

題解:這題跑一下bfs就好了,用一個數x表示此時n盞燈的狀態,二進制爲 1 表示燈開。所以最後只要判斷x爲0,所有燈就關了。

#include<bits/stdc++.h>
using namespace std;
const int M = (1 << 11);
struct node{
	int pre, step; 
};
int mp[110][110], vis[M];
int n, m, mx;
void bfs(){
	queue<node>q;
	q.push(node{mx, 0});
	vis[mx] = 1;
	while(!q.empty()){
		node t = q.front();
		q.pop();
		for(int i = 1; i <= m; ++i){
			int now = t.pre;
			for(int j = 1; j <= n; ++j){
				if(mp[i][j] == 1){
					if((now>>(j - 1)) & 1) // 判斷這一位是否爲1 
						now = now ^ (1<<(j - 1)); // 變成 0 
				}
				else if(mp[i][j] == -1)
					now = now | (1<<(j - 1)); // 變成1 
			}
			if(now == 0){
				cout<<t.step + 1<<endl;
				vis[now] = 1;
				return;
			}
			if(vis[now]) continue;
			q.push(node{now, t.step + 1});
			vis[now] = 1;
		}
	}
}
int main()
{
	cin>>n>>m;
	for(int i = 1; i <= m; ++i)
		for(int j = 1; j <= n; ++j)
			scanf("%d", &mp[i][j]);
	mx = (1<<n) - 1;
	bfs();
	if(!vis[0]) puts("-1");
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章