【图】最短路径Bellman-Ford算法

#include<iostream>
using namespace std;

const int max_num = 500;
const int max_len = 10000;
typedef struct Edge{
    int begin;//起点 
    int end;//终点 
    int weight;//权值 
}Edge;
class BellmanFord{
public:
    void read_case();
    void print_result();
    void print_path(int end);
private:
    bool bellman_ford();
private:
    int node_num;//图的结点数  
    int edge_num;//图的路径数 
    int start; //源点
    Edge edge[max_num];
    int distance[max_num];//结点到源点最小距离
    int pre[max_num];//源点到节点的路径
};
void BellmanFord::read_case(){
    cin >> node_num >> edge_num >> start;
    for (int i = 1; i <= edge_num; i++){
        distance[i] = max_num;
        pre[i] = i;
    }

    distance[start] = 0;
    for (int i = 1; i <= edge_num; i++){
        cin >> edge[i].begin >> edge[i].end >> edge[i].weight;
        if (edge[i].begin == start){//注意这里设置初始情况
            distance[edge[i].end] = edge[i].weight;
            pre[edge[i].end] = start;
        }
    }
}
bool BellmanFord::bellman_ford(){
    for (int i = 1; i < node_num; i++){
        for (int j = 1; j <= edge_num; j++){//松弛计算
            if (distance[edge[j].end]>distance[edge[j].begin] + edge[j].weight){
                distance[edge[j].end] = distance[edge[j].begin] + edge[j].weight;
                pre[edge[j].end] = edge[j].begin;
            }
        }
    }
    bool flag = true;
    //判断是否有负环路
    for (int j = 1; j <= edge_num; j++){
        if (distance[edge[j].end]>distance[edge[j].begin] + edge[j].weight){
            flag = false;
            break;
        }
    }
    return flag;
}
void BellmanFord::print_result(){
    if (bellman_ford())
    for (int i = 1; i <= node_num; i++){
        cout << distance[i] << endl;
        print_path(i);
    }

    else
        cout << "有负环" << endl;
}
void BellmanFord::print_path(int end){
    int que[max_num];
    int count = 1;
    que[count] = end;
    count++;
    int tmp = pre[end];
    while (tmp != start){
        que[count] = tmp;
        count++;
        tmp = pre[tmp];
    }
    que[count] = start;
    cout << "源点到顶点"<<end<<"的路径为: ";
    for (int i = count; i >= 1; i--)
    if (i != 1)
        cout << que[i] << " -> ";
    else
        cout << que[i] << endl;
}

int main(){
    BellmanFord bellman_ford;
    bellman_ford.read_case();
    bellman_ford.print_result();

    return 0;
}

你可能感兴趣的:(【图】最短路径Bellman-Ford算法)