POJ-2387 Til the Cows Come Home
阿新 • • 發佈:2018-12-09
最短路問題
題目大意: 有好多相通的路,路都有一定的長度,求1 到 n 的最短距離,單源最短路
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;
}