蓝桥杯 最短路 C++算法训练 HERODING的蓝桥杯之路

资源限制
时间限制:1.0s 内存限制:256.0MB
问题描述

给定一个n个顶点,m条边的有向图(其中某些边权可能为负,但保证没有负环)。请你计算从1号点到其他点的最短路(顶点从1到n编号)。
输入格式

第一行两个整数n, m。

接下来的m行,每行有三个整数u, v, l,表示u到v有一条长度为l的边。
输出格式
共n-1行,第i行表示1号点到i+1号点的最短路。
样例输入
3 3
1 2 -1
2 3 -1
3 1 2
样例输出
-1
-2
数据规模与约定

对于10%的数据,n = 2,m = 2。

对于30%的数据,n <= 5,m <= 10。

对于100%的数据,1 <= n <= 20000,1 <= m <= 200000,-10000 <= l <= 10000,保证从任意顶点都能到达其他所有顶点。

解题思路:
看到“最短路”三字,我就知道那三大最短路径算法要从我的仓库中出来了:贝尔曼福特算法、迪杰斯特拉算法、弗洛伊德算法。再仔细一看,该题限定了没有负环,且有负数权重,那么最好的选择便是贝尔曼福特算法了。感兴趣的朋友们可以面向百度查看贝尔曼福特算法的具体实现过程,这里我就不多叙述了。该题需要注意的方面有:
1.最短距离初始值一定要设得大,不然结果很可能没有变化,都是设定的初始值。
2.建议用结构体实现边,用类的方式麻烦了。没那个必要。
3.注意更新距离的初始条件。

代码如下:

#include<bits/stdc++.h>

#define INF 65535

using namespace std;

struct Edge{
	int from;
	int to;
	int cost;
};


Edge es[200001];

int d[20001];

void shortest_path(int s, int n, int m) {
	int i;
	for (i = 0; i < n; i ++){
		d[i] = INF;
	}
	d[s] = 0;
	while(true) {
		bool update = false;
		for (i = 0; i < m; i ++) {
			Edge e = es[i];
			if(d[e.from - 1] != INF && d[e.to - 1] > d[e.from - 1] + e.cost) {
				d[e.to - 1] = d[e.from - 1] + e.cost;
				update = true;
			}
		}
		if (!update) break;
	}
	
}

int main() {
	int n, m;//n个顶点 m条边
	cin >> n >> m; 
	for (int i = 0; i < m; i ++) {
		cin >> es[i].from >> es[i].to >> es[i].cost;
	}
	shortest_path(0, n, m);
	for (int i = 1; i < n; i ++) {
		cout << d[i] << endl;
	}
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/HERODING23/article/details/105832319