Description
Bessie is out in the field and wants to get back to the barn to get as much sleep as possible before Farmer John wakes her for the morning milking. Bessie needs her beauty sleep, so she wants to get back as quickly as possible. Farmer John's field has N (2 <= N <= 1000) landmarks in it, uniquely numbered 1..N. Landmark 1 is the barn; the apple tree grove in which Bessie stands all day is landmark N. Cows travel in the field using T (1 <= T <= 2000) bidirectional cow-trails of various lengths between the landmarks. Bessie is not confident of her navigation ability, so she always stays on a trail from its start to its end once she starts it. Given the trails between the landmarks, determine the minimum distance Bessie must walk to get back to the barn. It is guaranteed that some such route exists.Input
* Line 1: Two integers: T and N * Lines 2..T+1: Each line describes a trail as three space-separated integers. The first two integers are the landmarks between which the trail travels. The third integer is the length of the trail, range 1..100.Output
* Line 1: A single integer, the minimum distance that Bessie must travel to get from landmark N to landmark 1.Sample Input
5 5 1 2 20 2 3 30 3 4 20 4 5 20 1 5 100Sample Output
90Hint
INPUT DETAILS: There are five landmarks. OUTPUT DETAILS:Bessie can get home by following trails 4, 3, 2, and 1.
题目大意:有N个点,给出从a点到b点的距离,当然a和b是互相可以抵达的,问从1到n的最短距离
解题思路:模版题,这题要注意的是有重边,直接一个dijkstra模板就行了
#include<stdio.h> #include<string.h> #include<math.h> #define inf 0x3f3f3f3f int ans[1100][1100],map[1100][1100]; int dis[1100]; int book[1100]; int n,t; void dijkstra() { int i,j,min,v; for(i=1;i<=n;i++) dis[i]=map[1][i];//初始化 book[1]=1; for(i=1;i<=n;i++) { min=inf; for(j=1;j<=n;j++) { if(!book[j]&&min>dis[j])//每次选取离源点最近的点松弛 { min=dis[j]; v=j; } } book[v]=1; for(j=1;j<=n;j++) { if(dis[j]>dis[v]+map[v][j]) //松弛 dis[j]=dis[v]+map[v][j]; } } return ; } int main(){ int i,j; int x,y,z; while(scanf("%d%d",&t,&n)!=EOF) { memset(book,0,sizeof(book)); for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { if(i==j) map[i][j]=0; else map[i][j]=inf; } } for(i=1;i<=t;i++) { scanf("%d%d%d",&x,&y,&z); if(map[x][y]>z) map[x][y]=map[y][x]=z; } dijkstra(); printf("%d\n",dis[n]); } return 0; }
Marcus-Bao 认证博客专家 推荐系统 ACM算法竞赛 机器学习 本科毕业于国内知名四非大学,现中国科学院大学博士生,中国科学院计算技术研究所vipl实验室,老年ACM铁牌退役选手,喜欢算法竞赛,会点数据结构和算法,熟悉c++,python等;现阶段研究方向主要为机器学习与数据挖掘,比较关注推荐系统,发过顶会,炼过丹,平时博客主要记录些关于算法、数据结构,人工智能技术以及平时看的论文总结分享等,欢迎大家关注我,一起多多交流共同进步!