题目链接:http://poj.org/problem;jsessionid=BD8B6B3DAC9D44B6ABB161CBB9AAF60D?id=2387
题意:在 n 个坐标上有 t 条通道,输出从 1 到 n 所有路径中 最短的路径的长度
路径起点 为 1 (固定),采用dijksual 算法
AC代码:
/* kuangbin专题四 最短路练习 A题 POJ 2383 Til the Cows Come Home 题意:给你t条路径之间的关系,问你从n点走到1的最短路是多少,Dijkstra写一遍就行 Dijkstra理解:从起点s开始找到与之相连最短的点s',标记s',再更新s到与s'相连的点s''的最短距离, 再从s''中找到到s的最短的一个,标记,再更新s到与s''相连的点的最短距离,循环往复, 总之:就是不断标记最短点,再从该点出发,继续寻找。直到标记所有的点,更新完所有dis[i]。 注意 会有双向边的数据 ;去最小即可 */ #include<cstdio> #include<iostream> #include<cstring> #include<algorithm> using namespace std ; #define len 1005 int map[len][len] ; // 地图 int visit[len] ; // 标记地图 // 区分 n 个点中的点是否已经加入最短路 int dis[len] ; // 计算距离 表示 1 到 len 的距离 // 记录从起点到其他点的距离 void Dijkstra( int n ) { memset(visit , 0 , sizeof(visit)) ; for(int i=1 ; i<=n ; i++){ dis[i] = map[1][i] ; // 记录从 1 到 i 的最小距离 } visit[1] = 1 ; int k ; for(int i=1 ; i<=n ; i++){ int minn = 100005 ; for(int j=1 ; j<= n ; j++){ // 先查找相邻最小边 if(!visit[j] && dis[j] < minn){ minn = dis[j] ; k = j ; // 记录相邻最小边的位置 } } visit[k] = 1 ; for(int j=1 ; j<=n ; j++){ // 探测 剩下没有加入最短路的点 并修改其到 第一个点的距离 if(!visit[j] && dis[j] > map[k][j] + dis[k]){ dis[j] = map[k][j] + dis[k] ; } } } return; } int main(){ int T , N , x , y , z ; while( scanf("%d%d" , &T , &N)!=EOF ){ //memset(map , 0x3f , sizeof(map)) ; // 各元素最大化 for(int i=1 ; i<=N ; i++){ for(int j=1 ; j<=N ; j++){ map[i][j] = 100005 ; } } for(int i=1 ; i<=T ; i++){ scanf("%d%d%d" , &x , &y , &z) ; if(map[x][y] > z ) // 题目中说 有双向地标 可能出现输入数据 map[i][j] 和 map[j][i] 不同 , map[x][y] = map[y][x] = z ; // 处理方案 : 取两者最小 } Dijkstra(N) ; printf("%d " , dis[N]) ; } return 0 ; }