ダイクストラのアルゴリズム(最短経路を出力)

タイトルの説明
n 点、m 個の無向エッジ、各エッジの長さ d とコスト p があるとすると、始点 s と終点 t が与えられ、始点から終点までの最短距離とそのコストを出力する必要があります。最短距離のルートが複数ある場合は、コストが最小のルートを出力します。

入力説明:
n、m を入力します。点の数は 1 ~ n で、m 本の線があり、各線には 4 つの数字 a、b、d、p があり、a と b の間にエッジがあることを示します。その長さは d、コストは p です。最後の行は 2 つの数値 s、t、開始点 s、終了点 t です。n と m が 0 になると入力が終了します。
(1<n<=1000, 0<m<100000, s != t)
出力の説明:
2 つの数値、最短距離とそのコストを含む行を出力します。
例1

入力
3 2
1 2 5 6
2 3 4
5 1 3
0 0
出力
9 11
—————————————————

#include <iostream>
#include <queue>
#include <vector>
using namespace std;
 
 
/* 图的信息 */
typedef struct Edge {
    
    
	int s;
	int e;
	int l;
	int c;
 
	Edge(int s, int e, int l, int c) {
    
    
		this->s = s;
		this->e = e;
		this->l = l;
		this->c = c;
	}
	void print() {
    
    
		printf("start:%d end:%d length:%d cost:%d \n",this->s,this->e,this->l,this->c);
	}
 
} Edge;
vector<Edge> graph[1001];
 
typedef struct Point {
    
    
	int num; // 点的编号
	int distanceFromStart; // 从源点的距离
 
	bool operator < (const Point& a) const {
    
    
		return  distanceFromStart > a.distanceFromStart;
	}
	Point(int n, int d) {
    
    
		this->num = n;
		this->distanceFromStart = d;
	}
 
} Point;
 
int n, m; // 1 ~ n 编号 ; m个边
int u, v; // 起点 终点
 
int INF = 9999999;
int dis[1001];
int cost[1001];
 
void print() {
    
    
	cout << "graph" << endl;
	for (int i = 1; i <= n; i ++) {
    
    
		cout << "index:" << i << endl;
		for (int j = 0; j <= graph[i].size() - 1; j++) {
    
    
			graph[i][j].print();
		}
 
	}
}
void dijkstra(int u) {
    
    
	priority_queue<Point> q;
	dis[u] = 0;
	cost[u] = 0;
	q.push(Point(u,0));
	while(!q.empty()) {
    
    
		int father = q.top().num;
//		cout << "father:" << father << endl;
		q.pop();
 
		for (int i = 0; i <= graph[father].size() - 1; i++) {
    
    
			int s = graph[father][i].s;
			int e = graph[father][i].e;
			int l = graph[father][i].l;
			int c = graph[father][i].c;
 
			if (dis[e] > dis[s] + l || (dis[e] == dis[s] + l && cost[e] > cost[s] + c)) {
    
    
				dis[e] = dis[s] + l;
				cost[e] = cost[s] + c;
				q.push(Point(e,dis[e]));
			}
 
 
		}
 
	}
 
	return ;
}
 
int main() {
    
    
	while (cin >> n >> m && n != 0 && m != 0) {
    
    
		// 初始化
		for (int i = 1; i <= n; i++) {
    
    
			graph[i].clear();
		}
		for (int i = 1; i <= n; i ++) {
    
    
			dis[i] = INF;
			cost[i] = 0;
		}
		// 输入
		int s,e,l,c;
		for (int i = 1; i <= m; i++) {
    
    
			cin >> s >> e >> l >> c;
//			cout << s << e << l << c << endl;
			graph[s].push_back(Edge(s, e, l, c));
			graph[e].push_back(Edge(e, s, l, c));
		}
//		print(); // 测试了 没问题
 
		//填充dis cost
		cin >> u >> v;
		dijkstra(u);
		cout << dis[v] << " " <<  cost[v] << endl;
 
 
	}
 
 
 
}
```c


おすすめ

転載: blog.csdn.net/qq_42671505/article/details/105541032