在每年的校赛里,所有进入决赛的同学都会获得一件很漂亮的t-shirt。但是每当我们的工作人员把上百件的衣服从商店运回到赛场的时候,却是非常累的!所以现在他们想要寻找最短的从商店到赛场的路线,你可以帮助他们吗?
Input
输入保证至少存在1条商店到赛场的路线。
Output
Sample Input
2 1
1 2 3
3 3
1 2 5
2 3 5
3 1 2
0 0
Sample Output
3
2
入门题,重在练习使用模板。
第一个模板:floyed
#include<stdio.h>
#define N 110
#define inf 99999999
int e[N][N];
int main()
{
int n,m,t1,t2,t3,i,j,k;
while(scanf("%d%d",&n,&m),(m+n)!=0)
{
for(i = 1; i <= n; i ++)
for(j = 1; j <= n; j ++)
if( i== j)
e[i][j] = 0;
else
e[i][j] = inf;
for(i = 1; i <= m; i ++)
{
scanf("%d%d%d",&t1,&t2,&t3);
e[t1][t2] = t3;
e[t2][t1] = t3;
}
for(k = 1; k <= n; k ++)
for(i = 1; i <= n; i ++)
for(j = 1; j <= n; j ++)
if(e[i][j] > e[i][k] + e[k][j])
e[i][j] = e[i][k] + e[k][j];
printf("%d\n",e[1][n]);
}
return 0;
}
第二个模板:dijsktra
#include<stdio.h>
#define N 110
#define inf 99999999
int e[N][N],dis[N],book[N];
int main()
{
int n,m,u,i,j,t1,t2,t3,count,min;
while(scanf("%d%d",&n,&m),(n+m)!=0)
{
for(i = 1; i <= n; i ++)
for(j = 1; j <= n; j ++)
if(i == j)
e[i][j] = 0;
else
e[i][j] = inf;
for(i = 1; i <= m; i ++)
{
scanf("%d%d%d",&t1,&t2,&t3);
e[t1][t2] = t3;
e[t2][t1] = t3;
}
for(i = 1; i <= n; i ++)
dis[i] = e[1][i];
book[1] = 1;
count = 1;
while(count < n)
{
min = inf;
for(i = 1; i <= n; i ++)
if(!book[i]&&dis[i] < min)
{
min = dis[i];
u = i;
}
book[u] = 1;
count ++;
for(i = 1; i <= n; i ++)
if(!book[i]&&dis[i]>dis[u]+e[u][i])
dis[i] = dis[u] + e[u][i];
}
printf("%d\n",dis[n]);
}
return 0;
}