UVa #658 It's not a Bug, it's a Feature! (例题11-6)

86 篇文章 0 订阅

和第七章的题目很像,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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值