Bellman-Ford算法的实现

参照了紫书,同时要注意存储相应的信息,打印的时候进行逆向打印即可,具体实现见如下代码:

#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<deque>
#include<functional>
using namespace std;

class Edge{
public:
	int x, y, w;
};

class Graph{
public:
	int n, m;//顶点和边
	vector<Edge> edge;
	vector<int> G[1005];
	int parent[1005];
	int dist[1005];
	int amount[1005];

	const int Inf = 0x3f3f3f3f;
	int inq[1005];

	void Init(){
		cin >> n >> m;
		for (int i = 0; i < m; i++){
			Edge temp;
			cin >> temp.x >> temp.y >> temp.w;
			edge.push_back(temp);
			G[temp.x].push_back(edge.size()-1);//边的编号从0开始
		}
		memset(inq,0,sizeof(inq));
		memset(dist,Inf,sizeof(dist));
		memset(amount, 0, sizeof(amount));
		memset(parent,-1,sizeof(parent));
	}

	void Print(int i){
		cout << "result:" << endl;
		for (int j = 2; j <= n; j++){
			cout << j << ":     ";
			if (dist[j] == Inf){
				cout << "does not exist" << endl;
				continue;
			}
			cout <<"length:  "<< dist[j] << " : ";
			vector<int> res;
			int k = j;
			res.push_back(k);
			while (parent[k] != -1){
				int ide = parent[k];
				res.push_back(edge[ide].x);
				k = edge[ide].x;
			}
			reverse(res.begin(),res.end());
			for (int t = 0; t < res.size(); t++){
				cout << res[t] << " ";
			}
			cout << endl;
		}
	}

	void Deal(int i){
		Init();
		dist[i] = 0;
		queue<int> q;
		q.push(i);
		inq[i] = true;
		while (!q.empty()){
			int id = q.front();
			inq[id] = false;
			q.pop();
			for (int j = 0; j < G[id].size(); j++){
				int ide = G[id][j];
				int from = edge[ide].x;
				int to = edge[ide].y;
				if (dist[from] == Inf) continue;
				if (dist[to] > dist[from] + edge[ide].w){
					dist[to] = dist[from] + edge[ide].w;
					parent[to] = ide;
					if (!inq[to]){
						amount[to]++;
						if (amount[to] >= n){
							cout << "Error" << endl;
							return;
						}
						inq[to] = true;
						q.push(to);
					}
				}
			}
		}
		Print(i);
		return;
	}
};

int main(){
	Graph a;
	a.Deal(1);
	system("pause");
	return 0;
}

/*
5 7
1 2 4
2 3 6
1 5 1
1 4 -8
5 4 -3
2 4 -2
4 3 -10

4 4
1 2 -1
2 3 2
3 4 3
4 1 -100
*/

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