和第七章的题目很像,dijkstra求隐式图最短路。
Run Time: 2.202s
#define UVa "LT11-6.658.cpp" //It's not a Bug, it's a Feature!
char fileIn[30] = UVa, fileOut[30] = UVa;
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<iostream>
#include<queue>
using namespace std;
//Global Variables. Reset upon Each Case!
const int maxn = 21, maxm = 100 + 5;
int n, m, cost[maxm], st, T = 0;
int before[maxm][maxn], after[maxm][maxn];
int dist[1<<maxn], vis[1<<maxn];
/
struct HeapNode {
int w, s;
HeapNode(int a, int b):w(a),s(b) {}
bool operator < (const HeapNode& rhs) const {
return w > rhs.w;
}
};
int dijkstra() {
priority_queue<HeapNode> q;
q.push(HeapNode(0, st));
vis[st] = 1;
dist[st] = 0;
while(!q.empty()) {
HeapNode u = q.top(); q.pop();
if(u.s == 0) {
printf("Fastest sequence takes %d seconds.\n\n", u.w);
return 1;
}
for(int i = 0; i < m; i ++) {
int available = 1;
for(int j = 0; j < n; j ++) {
if((1<<j) & u.s) {
if(before[i][j] == -1) {
available = 0;
break;
}
}
else {
if(before[i][j] == 1) {
available = 0;
break;
}
}
}
if(!available) continue;
int v = u.s;
for(int j = 0; j < n; j ++) {
if(after[i][j] == 1) v |= (1<<j);
else if(after[i][j] == -1) v &= ~(1<<j);
}
if(vis[v] != T || dist[v] > u.w + cost[i]) {
vis[v] = T;
dist[v] = u.w + cost[i];
q.push(HeapNode(u.w + cost[i], v));
}
}
}
return 0;
}
int main() {
memset(vis, 0, sizeof(vis));
int code[200];
code['0'] = 0, code['+'] = 1, code['-'] = -1;
while(scanf("%d%d", &n, &m) && n) {
printf("Product %d\n", ++T);
char s1[maxn], s2[maxn];
for(int i = 0; i < m; i ++) {
scanf("%d%s%s", &cost[i], s1, s2);
for(int j = 0; j < n; j ++) {
before[i][j] = code[s1[j]];
after[i][j] = code[s2[j]];
}
}
st = (1<<n)-1;
if(!dijkstra()) {
printf("Bugs cannot be fixed.\n\n");
}
}
return 0;
}