MiYu原創(chuàng), 轉(zhuǎn)帖請(qǐng)注明 : 轉(zhuǎn)載自 ______________白白の屋
題目地址:
http://acm.hdu.edu.cn/showproblem.php?pid=1874
題目描述:
暢通工程續(xù)
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5528 Accepted Submission(s): 1686
Problem Description
某省自從實(shí)行了很多年的暢通工程計(jì)劃后,終于修建了很多路。不過(guò)路多了也不好,每次要從一個(gè)城鎮(zhèn)到另一個(gè)城鎮(zhèn)時(shí),都有許多種道路方案可以選擇,而某些方案要比另一些方案行走的距離要短很多。這讓行人很困擾。
現(xiàn)在,已知起點(diǎn)和終點(diǎn),請(qǐng)你計(jì)算出要從起點(diǎn)到終點(diǎn),最短需要行走多少距離。
Input
本題目包含多組數(shù)據(jù),請(qǐng)?zhí)幚淼轿募Y(jié)束。
每組數(shù)據(jù)第一行包含兩個(gè)正整數(shù)N和M(0<N<200,0<M<1000),分別代表現(xiàn)有城鎮(zhèn)的數(shù)目和已修建的道路的數(shù)目。城鎮(zhèn)分別以0~N-1編號(hào)。
接下來(lái)是M行道路信息。每一行有三個(gè)整數(shù)A,B,X(0<A,B<N,A!=B,0<X<10000),表示城鎮(zhèn)A和城鎮(zhèn)B之間有一條長(zhǎng)度為X的雙向道路。
再接下一行有兩個(gè)整數(shù)S,T(0<=S,T<N),分別代表起點(diǎn)和終點(diǎn)。
Output
對(duì)于每組數(shù)據(jù),請(qǐng)?jiān)谝恍欣镙敵鲎疃绦枰凶叩木嚯x。如果不存在從S到T的路線,就輸出-1.
Sample Input
3 3
0 1 1
0 2 3
1 2 1
0 2
3 1
0 1 1
1 2
Sample Output
2
-1
題目分析:
最短路的入門(mén)題目.
Dijkstra算法的基本思路是:
假設(shè)每個(gè)點(diǎn)都有一對(duì)標(biāo)號(hào) (dj, pj),其中dj是從起源點(diǎn)s到點(diǎn)j的最短路徑的長(zhǎng)度 (從頂點(diǎn)到其本身的最短路徑是零路(沒(méi)有弧的路),其長(zhǎng)度等于零);
pj則是從s到j(luò)的最短路徑中j點(diǎn)的前一點(diǎn)。求解從起源點(diǎn)s到點(diǎn)j的最短路徑算法的基本過(guò)程如下:
1) 初始化。起源點(diǎn)設(shè)置為:① ds=0, ps為空;② 所有其他點(diǎn): di=∞, pi=?;③ 標(biāo)記起源點(diǎn)s,記k=s,其他所有點(diǎn)設(shè)為未標(biāo)記的。
2) 檢驗(yàn)從所有已標(biāo)記的點(diǎn)k到其直接連接的未標(biāo)記的點(diǎn)j的距離,并設(shè)置:
dj=min[dj, dk+lkj]
式中,lkj是從點(diǎn)k到j(luò)的直接連接距離。
3) 選取下一個(gè)點(diǎn)。從所有未標(biāo)記的結(jié)點(diǎn)中,選取dj 中最小的一個(gè)i:
di=min[dj, 所有未標(biāo)記的點(diǎn)j]
點(diǎn)i就被選為最短路徑中的一點(diǎn),并設(shè)為已標(biāo)記的。
4) 找到點(diǎn)i的前一點(diǎn)。從已標(biāo)記的點(diǎn)中找到直接連接到點(diǎn)i的點(diǎn)j*,作為前一點(diǎn),設(shè)置:i=j*
5) 標(biāo)記點(diǎn)i。如果所有點(diǎn)已標(biāo)記,則算法完全推出,否則,記k=i,轉(zhuǎn)到2) 再繼續(xù)。
代碼如下:
#include <iostream>
using namespace std;
const int MAX = 201;
const int INF = 0x7FFFFFF;
int graph[MAX][MAX];
bool hash[MAX];
int path[MAX];
int N,M;
int Dijkstra ( int beg , int end )
{
path[beg] = 0;
hash[beg] = false;
while ( beg != end )
{
int m = INF, temp;
for ( int i = 0; i != N; ++ i )
{
if ( graph[beg][i] != INF )
path[i] = min ( path[i], path[beg] + graph[beg][i] );
if ( m > path[i] && hash[i] )
{
m = path[i];
temp = i;
}
}
beg = temp;
if ( m == INF )
break;
hash[beg] = false;
}
if ( path[end] == INF )
return -1;
return path[end];
}
int main ()
{
while ( scanf ( "%d%d", &N, &M ) != EOF )
{
for ( int i = 0; i != MAX; ++ i )
{
hash[i] = true;
path[i] = INF;
for ( int j = 0; j != MAX; ++ j )
{
graph[i][j] = INF;
}
}
for ( int i = 0; i != M; ++ i )
{
int c1,c2,cost;
scanf ( "%d%d%d",&c1, &c2, &cost );
if ( cost < graph[c1][c2] )
graph[c1][c2] = graph[c2][c1] = cost;
}
int beg,end;
scanf ( "%d%d",&beg, &end );
cout << Dijkstra ( beg,end ) << endl;
}
return 0;
}