Problem Description
某省自从实行了很多年的畅通工程计划后,终于修建了很多路。不过路多了也不好,每次要从一个城镇到另一个城镇时,都有许多种道路方案可以选择,而某些方案要比另一些方案行走的距离要短很多。这让行人很困扰。

现在,已知起点和终点,请你计算出要从起点到终点,最短需要行走多少距离。
 

 

Input
本题目包含多组数据,请处理到文件结束。
每组数据第一行包含两个正整数N和M(0<N<200,0<M<1000),分别代表现有城镇的数目和已修建的道路的数目。城镇分别以0~N-1编号。
接下来是M行道路信息。每一行有三个整数A,B,X(0<=A,B<N,A!=B,0<X<10000),表示城镇A和城镇B之间有一条长度为X的双向道路。
再接下一行有两个整数S,T(0<=S,T<N),分别代表起点和终点。
 

 

Output
对于每组数据,请在一行里输出最短需要行走的距离。如果不存在从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

 思路:裸的最小路径问题

 1 #include<iostream>
 2 #include<stdio.h>
 3 #include<string.h>
 4 #include<stdlib.h>
 5 #include<math.h>
 6 #include<algorithm>
 7 #define LL long long
 8 #define mod 1e9 + 7
 9 #define MAX 10000000
10 const int M = 205;
11 
12 using namespace std;
13 
14 int main()
15 {
16     int n, m;
17     int map[M][M], dis[M], vis[M];
18     int min;
19     int a, b, c, temp, p, q;
20     while( cin >> n >> m )
21     {
22         for(int i = 0; i <= n; ++i)
23             for(int j = 0; j <= n; ++j)
24                 map[i][j] = MAX;
25         memset(vis,0,sizeof(vis));
26         for(int i = 0; i < m; ++i)
27         {
28             scanf("%d%d%d",&a,&b,&c);
29             if(map[a][b] > c)
30                 map[a][b] = map[b][a] = c;
31         }
32         cin >> p >> q;
33         for(int i = 0; i < n; ++i)
34             dis[i] = map[p][i];
35         dis[p] = 0;
36         for(int i = 0; i < n - 1; ++i)
37         {
38             min = MAX;
39             for(int j = 0; j < n; ++j)
40             {
41                 if(!vis[j] && min > dis[j])
42                 {
43                     min = dis[j];
44                     temp = j;
45                 }
46             }
47             if(min == MAX)
48                 break;
49             vis[temp] = 1;
50             for(int j = 0; j < n; ++j)
51                 if(!vis[j] && dis[temp] + map[temp][j] < dis[j])
52                     dis[j] = dis[temp] + map[temp][j];
53         }
54         if(dis[q] == MAX)
55             dis[q] = -1;
56         cout << dis[q] << endl;
57     }
58     return 0;
59 }
View Code

 

posted on 2014-08-08 16:45  Unico  阅读(129)  评论(0)    收藏  举报