码迷,mamicode.com
首页 > 其他好文 > 详细

PAT 旅游规划

时间:2015-06-03 15:14:17      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

旅游规划

 

有了一张自驾旅游路线图,你会知道城市间的高速公路长度、以及该公路要收取的过路费。现在需要你写一个程序,帮助前来咨询的游客找一条出发地和目的地之间的最短路径。如果有若干条路径都是最短的,那么需要输出最便宜的一条路径。

 

考察dijkstra算法   要注意的是  当权重相等时 要更新下费用

 

AC代码

 1 #include <stdio.h>
 2 #define MAX 100000
 3 typedef struct
 4 {
 5     int weight;
 6     int cost;
 7 }graph;
 8 int N,M,S,D;
 9 graph g[500][500];
10 int dis[500];
11 int cost[500];
12 int flag[500];
13 void Dijkstra(int v)
14 {
15     int min,i,j,pos;
16     
17     for(i=0;i<N;i++)
18     {
19         if(g[v][i].weight>0 )
20         {
21             dis[i]=g[v][i].weight;    
22             cost[i]=g[v][i].cost;
23         }        
24     }
25     flag[v]=1;
26     for(i=0;i<N;i++)
27     {
28         min=MAX;
29         pos=v;
30         for(j=i;j<N;j++)
31         {
32             if(flag[j]!=1 &&dis[j]<min &&dis[j]>0)
33             {
34                 min=dis[j];
35                 pos=j;
36             }
37         }
38         flag[pos]=1;
39     
40         for(j=0;j<N;j++)
41         {
42             if(flag[j]!=1&&dis[pos]+g[pos][j].weight<dis[j] &&g[pos][j].weight>0&&dis[j]>0)
43             {
44                 dis[j]=dis[pos]+g[pos][j].weight;
45                 cost[j]=cost[pos]+g[pos][j].cost;
46             }
47             else if(dis[pos]+g[pos][j].weight==dis[j] &&cost[j]>cost[pos]+g[pos][j].cost)
48             {
49                 cost[j]=cost[pos]+g[pos][j].cost;
50             }
51         }
52     }
53     printf("%d %d\n",dis[D],cost[D]);    
54 }
55 main()
56 {
57     int a,b,l,c;
58     int i,j;
59     scanf("%d%d%d%d",&N,&M,&S,&D);
60     for(i=0;i<M;i++)
61     {
62         scanf("%d%d%d%d",&a,&b,&l,&c);
63         g[a][b].weight=g[b][a].weight=l;
64         g[a][b].cost=g[b][a].cost=c;
65     }
66     Dijkstra(S);
67 }

 

PAT 旅游规划

标签:

原文地址:http://www.cnblogs.com/threezj/p/4549083.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!