一道简单的题目,利用二进制的每一位来对应Bug的每一位,然后进行状态转移即可,在状态转移之前要记得判断当前的bug的情况是否满足转移的要求,同时在状态转移之后要判断转移的时间是否更短了,如果更短要记得更新,并且要将相应的状态放到队列当中,为下一次转移的操作做铺垫,具体实现见如下代码:
#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<deque>
#include<functional>
using namespace std;
const int INF = 0x3f3f3f3f;
const int Inf = 1 << 20;
int dist[Inf + 10];
class Bug{
public:
int dist, bug;
bool operator< (const Bug& a)const{
return dist > a.dist;
}
};
class Solve{
public:
int n, m;
string before[110], after[110];
int Time[110];
void Init(){
memset(dist,INF,sizeof(dist));
for (int i = 0; i < m; i++){
cin >>Time[i]>> before[i] >> after[i];
}
}
int Deal(){
Init();
priority_queue<Bug, vector<Bug>> pq;
Bug start;
start.bug = (1 << n) - 1;
start.dist = 0;
pq.push(start);
while (!pq.empty()){
Bug temp = pq.top();
if (temp.bug == 0) return temp.dist;
pq.pop();
for (int i = 0; i < m; i++){
bool use = true;
for (int j = 0; j < n; j++){
if (before[i][j] == '-' && (temp.bug&(1 << j))){ use = false; break; }
if (before[i][j] == '+'&&!(temp.bug&(1 << j))){ use = false; break; }
}
if (!use) continue;
Bug nxt=temp;
for (int j = 0; j < n; j++){
if (after[i][j] == '+') nxt.bug |= (1 << j);
if (after[i][j] == '-') nxt.bug &= ~(1 << j);
}
nxt.dist += Time[i];
int& amount = dist[nxt.bug];
if (amount<0||amount > nxt.dist){
amount = nxt.dist;
pq.push(nxt);
}
}
}
return -1;
}
};
int main(){
Solve a;
int Case = 0;
while (cin >> a.n >> a.m){
if (a.n == 0 && a.m == 0) break;
Case++;
int res = a.Deal();
cout << "Product " << Case << endl;
if (res == -1){
cout << "Bugs cannot be fixed.\n\n";
}
else{
cout << "Fastest sequence takes "<<res<<" seconds.\n\n";
}
}
return 0;
}
/*
3 3
1 000 00-
1 00- 0-+
2 0-- -++
4 1
7 0-0+ ---0
*/