hdu 1874 畅通工程续(bellman-ford,dijkstra)

bellman-ford:
#include <stdio.h>
#define INF 99999999
int u[2200],v[2200],w[2200];
int dis[210];
int main()
{
    int n,m,i,k;
    while(scanf("%d %d",&n,&m) != EOF)
    {
        for(i = 0; i < m; ++i)
        {
            scanf("%d %d %d",&u[i],&v[i],&w[i]);
            u[i+m] = v[i];
            v[i+m] = u[i];
            w[i+m] = w[i];
        }
        int start,end;
        scanf("%d %d",&start,&end);
        for(i = 0; i < n; ++i)
            dis[i] = INF;
        dis[start] = 0;
        for(k = 0; k < n; ++k)
            for(i = 0; i < 2*m; ++i)
                if(dis[v[i]] > dis[u[i]] + w[i])
                    dis[v[i]] = dis[u[i]] + w[i];
        if(dis[end] < INF)
            printf("%d\n",dis[end]);
        else
            printf("-1\n");
    }
    return 0;
}

dijkstra:

#include <iostream>
#include <cstring>
using namespace std;
#define INF 99999999
int map[200][200];
int dis[200];
int book[200];
int n,m;
int main()
{
    int S,T,i,k,j,x,y,z;
    while(cin >> n >> m)
    {
        for(i = 0; i < n; ++i)
            for(j = 0; j < n; ++j)
                if(i == j) map[i][j] = 0;
                else map[i][j] = INF;

        for(i = 0; i < m; ++i)
        {
            cin >> x >> y >> z;
            if(z < map[x][y])
                map[x][y] = map[y][x] = z;
        }
        memset(book,0,sizeof(book));
        cin >> S >> T;
        for(i = 0; i < n; ++i)
            dis[i] = map[S][i];
        book[S] = 1;
        int min = INF;
        int u,v;
        for(k = 0; k < n; ++k)
        {
            min = INF;
            for(i = 0; i < n; ++i)
                if(!book[i] && min > dis[i]){ min = dis[i]; u = i;}
            book[u] = 1;
            for(v = 0; v < n; ++v)
                dis[v] = dis[v] < dis[u]+map[u][v] ? dis[v]:dis[u]+map[u][v];
        }
        if(dis[T] != INF)
            cout << dis[T] << endl;
        else
            cout << "-1" << endl;
    }
    return 0;
}

    原文作者:Bellman - ford算法
    原文地址: https://blog.csdn.net/gyhguoge01234/article/details/51541752
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞