洛谷P2622 关灯问题II【状压dp+bfs】
生活随笔
收集整理的這篇文章主要介紹了
洛谷P2622 关灯问题II【状压dp+bfs】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
P2622 關燈問題II
題目描述
現有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
解題思路:
由于最多只有10盞燈,所以我們可以用一個數dpdpdp來直接表示燈的狀態,然后將初始狀態放入隊列,每次取隊首狀態,遍歷各個開關,將進行操作后的新狀態放入隊列,不停bfs紙質找到結果即可。
代碼:
#include <cstdio> #include <iostream> #include <algorithm> #include <cmath> #include <cstdlib> #include <cstring> #include <map> #include <stack> #include <queue> #include <vector> #include <bitset> #include <set> #include <utility> #include <sstream> #include <iomanip> using namespace std; typedef long long ll; typedef unsigned long long ull; #define inf 0x3f3f3f3f #define rep(i,l,r) for(int i=l;i<=r;i++) #define lep(i,l,r) for(int i=l;i>=r;i--) #define ms(arr) memset(arr,0,sizeof(arr)) //priority_queue<int,vector<int> ,greater<int> >q; const int maxn = (int)1e5 + 5; const ll mod = 1e9+7; int a[120][12]; struct node {int dp;int step; }; int n,m; bool vis[3000]; int change(int x,int id,int wei) {int nape=x&(1<<(wei-1));if(nape==(1<<(wei-1))&&id==1) {return x^(1<<(wei-1));}if(nape==0&&id==-1) {return x|(1<<(wei-1));}return x; } int bfs() {queue<node> q;while(!q.empty()) {q.pop();}node s;s.dp=(1<<m)-1;s.step=0;memset(vis,false,sizeof vis);vis[s.dp]=true;q.push(s);node nape;while(!q.empty()) {node fro=q.front();q.pop();if(fro.dp==0) {return fro.step;}for(int i=1;i<=n;i++) {nape.dp=fro.dp;for(int j=1;j<=m;j++) {nape.dp=change(nape.dp,a[i][j],j);//cout<<j<<" "<<(nape.dp&(1<<(j-1)))<<" "<<nape.dp<<endl;}nape.step=fro.step+1;if(vis[nape.dp]==false) {vis[nape.dp]=true;q.push(nape);}}}return -1; } int main() {#ifndef ONLINE_JUDGEfreopen("in.txt", "r", stdin);#endif//freopen("out.txt", "w", stdout);//ios::sync_with_stdio(0),cin.tie(0);scanf("%d %d",&m,&n);rep(i,1,n) {rep(j,1,m) {scanf("%d",&a[i][j]);}}int ans=bfs();printf("%d\n",ans);return 0; }總結
以上是生活随笔為你收集整理的洛谷P2622 关灯问题II【状压dp+bfs】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 马鞍点问题【数组】
- 下一篇: Problem C: 顺序表基本运算(线