题意:程序有n个bug,要全部修正这些bug。现有n个补丁,每个补丁有打补丁之前的状态要求,和打完之后的状态以及打补丁的花费。问需要最少多少花费才能修正所有的Bug。

分析:每个状态用二进制表示为图上的点,补丁作为作为图上的边,花费作为权值,用Dijkstra算法求最短路即可。

CPP代码如下:

 

#include <bits/stdc++.h>
using namespace std;

struct Patch{
    int price;
    char a[25], b[25];
}pa[105];
typedef pair<int, int> P;
const int inf = 0x3f3f3f3f;
int n, m, kase, d[1<<20];


int Debug(int x, char *a, char *b) {
    for(int i = 0; i < n; ++i) {
        if(a[i] == '-' && (x&(1<<i))) return -1;
        if(a[i] == '+' && !(x&(1<<i))) return -1;
    }
    int y = x;
    for(int i = 0; i < n; ++i) {
        if(b[i] == '-') y &= ~(1<<i);
        if(b[i] == '+') y |= (1<<i);
    }
    return y;
}

int Dijkstra() {
    memset(d, inf, sizeof(d));
    d[(1<<n)-1] = 0;
    priority_queue<P, vector<P>, greater<P>> qu;
    qu.push(P(0, (1<<n)-1));

    while (!qu.empty()) {
        P p = qu.top(); qu.pop();
        int v = p.second;
        if(v == 0) return p.first;
        if(d[v] < p.first) continue;
        for (int i = 0; i < m; ++i) {
            int res = Debug(v, pa[i].a, pa[i].b);
            if(res == -1) continue;
            if (d[res] > d[v] + pa[i].price) {
                d[res] = d[v] + pa[i].price;
                qu.push(P(d[res], res));
            }
        }
    }
    return -1;
}

int main() {
    while (scanf("%d%d", &n, &m), n || m) {
        for (int i = 0; i < m; ++i)
            scanf("%d%s%s", &pa[i].price, pa[i].a, pa[i].b);
        int res = Dijkstra();
        printf("Product %d\n", ++kase);
        if (res == -1) printf("Bugs cannot be fixed.\n");
        else printf("Fastest sequence takes %d seconds.\n", res);
        printf("\n");
    }
    return 0;
}

欢迎留言