首页 > 其他 > 详细

题解—基础最短路 bellman-ford

时间:2020-08-19 22:16:13      阅读:73      评论:0      收藏:0      [点我收藏+]

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

最短路基础题,使用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 n, m, sum, cnt;

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

void bellman_ford(int start, int end)
{
    int s = start;
    int d[205];
    for (int i = 0; i < n; i++) d[i] = INF;
    d[s] = 0;
    for (int k = 1; k <= n; 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;
            }
        }
    }
    if (d[end] != INF) sum = d[end];
    else sum = -1;
}

int main()
{
    while (cin >> n >> m)
    {
        cnt = 0;
        sum = 0;
        for (int i = 1; i <= m; i++)
        {
            int u, v, w;
            cin >> u >> v >> w;
            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++;
        }
        int a, b;
        cin >> a >> b;
        bellman_ford(a, b);
        cout << sum << endl;
    }
    return 0;
}

 

题解—基础最短路 bellman-ford

原文:https://www.cnblogs.com/zny0222/p/13531723.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!