题解—基础最短路 N次bellman-ford

题目链接:https://cn.vjudge.net/contest/388653#problem/C

由于有多个起点,遍历起点进行n次bellman-ford,并每次遍历终点,取最小值。

#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <string>
#include <cmath>
#include <vector>
#include <queue>

using namespace std;
typedef long long ll;

const int INF = 1e9 + 7;
const int Max = 10005;

int T, S, D, sum, cnt, maxn;
int st[1005], ed[1005];

struct edge
{
    int from, to, value;
}e[Max];

void bellman_ford(int start)
{
    int s = start;
    int d[1010];
    for (int i = 1; i <= 1005; i++) d[i] = INF;
    d[s] = 0;
    for (int k = 1; k <= maxn; k++)
    {
        for (int i = 0; i < cnt; i++)
        {
            int x = e[i].from; int y = e[i].to;
            if (d[x] > d[y] + e[i].value)
            {
                d[x] = d[y] + e[i].value;
            }
        }
    }
    for (int i = 1; i <= D; i++)
    {
        if (d[ed[i]] < sum && d[ed[i]] != INF)
            sum = d[ed[i]];
    }
}

int main()
{
    while (cin >> T >> S >> D)
    {
        cnt = 0;
        sum = INF; // 方便寻找最小答案
        maxn = 0;
        for (int i = 1; i <= T; i++)
        {
            int u, v, w;
            cin >> u >> v >> w;
            maxn = max(maxn, max(u, v)); // 记录编号最大的城市
            e[cnt].from = u; e[cnt].to = v; e[cnt].value = w; cnt++;
            e[cnt].from = v; e[cnt].to = u; e[cnt].value = w; cnt++;
        }
        for (int i = 1; i <= S; i++) cin >> st[i];
        for (int i = 1; i <= D; i++) cin >> ed[i];
        for (int i = 1; i <= S; i++)
        {
            bellman_ford(st[i]);
        }
        cout << sum << endl;
    }
    return 0;
}

 

posted @ 2020-08-19 20:36  章楠雨  阅读(132)  评论(0编辑  收藏  举报