http://acm.nefu.edu.cn/JudgeOnline/contestshow.php?contest_id=120&problem_id=207&num=2
description |
有n个站,求从1站到n站的最短路线。
|
input |
输入第一行n和m, n表示有n个站,m表示有m条道路,(n,m<100)接下来m行每一行输入三个数a,b,d,表示a和b之间有一条长为d 的路。
|
output |
输出从1到n的最短距离。
|
sample_input |
5 4
1 2 1
1 5 5
2 4 2
4 5 1
2 1
1 2 3
|
sample_output |
4
3 |
下面是我的代码:
#include <stdio.h>
#include <iostream>
#include <string.h>
#define MAX 99999
#define LEN 101
using namespace std;
int map[LEN][LEN];
void abc()
{
int i,j;
for(i=0;i<LEN ;i++)
{
for(j=0;j<LEN;j++)
map[i][j]=MAX;
}
}
void prime(int n)
{
int i,j,k;
for(k=0;k<n;k++)//Floyd算法的精髓,时间复杂度o(n^3)
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(map[i][j]>map[i][k]+map[k][j])
map[i][j]=map[i][k]+map[k][j];
}
int main()
{
abc();
int m,n,a,b,c,d,w,i;
while(~scanf("%d%d",&n,&m))
{
for(i=0;i<m;i++)
{
cin>>a>>b>>w;
if(map[a][b]>w)
map[a][b]=w;
}
cin >> c>> d;
prime(n);
if(map[c][d]==MAX)
cout << "-1\n";
else
cout << map[c][d] << endl;
}
return 0;
}

508

被折叠的 条评论
为什么被折叠?



