Bellman-Ford

《挑戰程序設計競賽》,初級篇–圖

// 單源最短路徑1(含負權邊) O(V*E)
// Bellman-Ford
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define maxv 101
#define maxe 101
#define INF 9999

struct edge
{
    int from,to;
    int cost;
};

edge es[maxe];
int d[maxv];
int V,E;

// 從點s出發,到所有點的最短距離
void shortest_path(int s)
{
    for(int i = 0; i < V; i++)
        d[i] = INF;
    d[s] = 0;
    while(true)
    {
        bool update = false;
        for(int i = 0; i < E; i++)
        {
            edge e = es[i];
            if(d[e.from] != INF && d[e.to] > d[e.from] + e.cost)
            {
                d[e.to] = d[e.from] + e.cost;
                update = true;
            }
        }
        if(!update) break;
    }
}

bool find_negative_loop()
{
    memset(d,0,sizeof(d));

    for(int i = 0; i < V; i++)
    {
        for(int j = 0; j < E; j++)
        {
            edge e = es[j];
            if(d[e.to] > d[e.from] + e.cost)
            {
                d[e.to] = d[e.from] + e.cost;
                if(i == V-1) return true;
            }
        }
    }
    return false;
}

int main()
{
    cin>>V>>E;
    for(int i = 0; i < E; i++)
        cin>>es[i].from>>es[i].to>>es[i].cost;
    shortest_path(0);
    printf("------------- \n");
    for(int i = 0; i < V; i++)
    {
        cout<<"該點到"<<i<<"點最短距離爲: ";
        cout<<d[i]<<endl;
    }
    return 0;   
}
/*
測試數據:
4 4
0 1 1
0 2 3
1 2 4
2 3 2
*/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章