##最短路问题
题目大意:
有好多相通的路,路都有一定的长度,求1 到 n 的最短距离,单源最短路
https://vjudge.net/problem/POJ-2387 链接
dijkstra :
思路就是贪心 从节点1 找 ,如果 节点i 到1 的距离 > 节点1到节点u + 节点u和节点i的距离 ,更新路径权值,这个算法只能计算单元最短路,而且不能计算负权值,
path数组储存节点1到各个节点的距离,所以初始化path[1] = 0; 其他的都是INF 然后不断更新
比如1到3的最短路就是比较path[3]与path[2]+cost[2][3],如果大于的话就更新path[3] = path[2]+cost[2][3],这个专业术语叫松弛,这种算法的核心思想就是通过边来松弛一号顶点到其他定点的路程
#include<iostream>
#include<string>
#include<cstring>
struct NOD
{
int from, to, cost;
}es[4040];
int path[1010];
const int INF = 0x3f3f3f3f;
void short_path(int t)
{
memset(path, 0x3f, sizeof path);
path[1] = 0;
while(true)
{
bool step = false;
for(int i = 0; i < 2*t; ++i)
{
if(path[es[i].from] != INF && path[es[i].to] > path[es[i].from] + es[i].cost)
{
step = true;
path[es[i].to] = path[es[i].from] + es[i].cost;
}
}
if(!step) break;
}
}
int main()
{
int n, t;
std::cin >> t >> n;
for(int i=0; i < t; ++i)
{
std::cin >> es[i].from >> es[i].to >> es[i].cost;
es[i+t].from = es[i].to;
es[i+t].to = es[i].from;
es[i+t].cost = es[i].cost;
}
short_path(t);
std::cout << path[n] << std::endl;
return 0;
}