要求
给出一个有向图,让你求start点到end点的最短距离
限制条件
无
输入格式
第一行输入V,E分别代表顶点数和边数
接下来E行,每行输入from to cost 代表从from到to的距离为cost
最后一行输入start end
输出格式
输出最短距离
测试输入
3 3
0 1 2
1 2 3
0 2 4
0 2
测试输出
4
解题思路
从start出发。不断维护每个点的最短距离。
代码
#include <iostream>
#include <cstring>
using namespace std;
#define MAX 10000000
class Node {
public:
int from;
int to;
int cost;
};
Node es[MAX];
int dist[MAX];
int V, E;
// 从s点到其他所有点的最短距离(最小cost)
void shortestPath(int s) {
fill(dist, dist + V, 0x7f7f);
dist[s] = 0;
while (true) {
bool update = false;
for (int i = 0; i < E; i++) {
Node e = es[i];
if (dist[e.from] != 0x7f7f && dist[e.to] > dist[e.from] + e.cost) {
dist[e.to] = dist[e.from] + e.cost;
update = true;
}
}
if (!update) {
break;
}
}
}
int main() {
cin >> V >> E;
for (int i = 0; i < E; i++) {
cin >> es[i].from >> es[i].to >> es[i].cost;
}
int start, end;
cin >> start >> end;
shortestPath(start);
cout << dist[end] << endl;
return 0;
}