hdu 2680 Choose the best route

        hdu 2680 Choose the best route

        反向建图, 然后计算终点到各点的最短路径.

#include <stdio.h>
#include <queue>
using namespace std;

#define MAX 1001
#define INF 0xffffff

int map[MAX][MAX];
bool visited[MAX];
int lowcost[MAX];
int go[MAX];
int n, m, s, to;

/*
void spfa(int s) {
    int i;
    int now;
    queue<int> Q;

    for (i = 1; i <= n; i++) {
        visited[i] = false;
        lowcost[i] = INF;
    }
    lowcost[s] = 0;
    visited[s] = true;
    Q.push(s);

    while (!Q.empty()) {
        now = Q.front();
        Q.pop();

        for (i = 1; i <= n; i++) {
            if (lowcost[now] + map[now][i] < lowcost[i]) {
                lowcost[i] = lowcost[now] + map[now][i];

                if (!visited[i]) {
                    visited[i] = true;
                    Q.push(i);
                }
            }
        }

        visited[now] = false;
    }
}*/


void dijk(int s) {
    int i, j;
    int v, min;

    for (i = 1; i <= n; i++) {
        visited[i] = false;
        lowcost[i] = map[s][i];
    }
    lowcost[s] = 0;
    visited[s] = true;

    for (i = 2; i <= n; i++) {
        min = INF;
        for (j = 1; j <= n; j++) {
            if (!visited[j] && min > lowcost[j]) {
                min = lowcost[j];
                v = j;
            }
        }
        if (min == INF) {
            return ;
        }
        visited[v] = true;

        for (j = 1; j <= n; j++) {
            if (!visited[j] && min + map[v][j] < lowcost[j]) {
                lowcost[j] = min + map[v][j];
            }
        }
    }
}

int main() {
    int i, j;
    int a, b, c;
    int ans;

    while (scanf("%d%d%d", &n, &m, &to) == 3) {
        ans = INF;
        for (i = 1; i <= n; i++) {
            for (j = 1; j <= n; j++) {
                if (i == j) {
                    map[i][j] = 0;
                } else {
                    map[i][j] = INF;
                }
            }
        }

        for (i = 0; i < m; i++) {
            scanf("%d%d%d", &a, &b, &c);
            if (c < map[b][a]) {
                map[b][a] = c;
            }
        }

        scanf("%d", &s);
        for (i = 0; i < s; i++) {
            scanf("%d", &go[i]);
        }

        // spfa(to);
        dijk(to);
        for (i = 0; i < s; i++) {
            if (ans > lowcost[go[i]]) {
                ans = lowcost[go[i]];
            }
        }

        if (ans == INF) {
            printf("-1\n");
        } else {
            printf("%d\n", ans);
        }
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值