HDU 1874 畅通工程续(dijkstra+优先队列)

畅通工程续




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<cstdio>
 2 #include<queue>
 3 #include<algorithm>
 4 #include<cstring>
 5 using namespace std;
 6 
 7 struct edge
 8 {
 9     int from,to,dist;
10     edge(int u,int v,int w):from(u),to(v),dist(w){};
11 };
12 
13 struct heapnode
14 {
15     int u,d;
16     bool operator < (const heapnode &temp)const
17     {
18         return d>temp.d;
19     }
20 };
21 
22 const int inf=0x3f3f3f3f;
23 int m,n;
24 vector<edge>edges;
25 vector<int>G[205]; 
26 int vis[205],d[205];
27 
28 void init()
29 {
30     for(int i=0;i<m;i++)
31     G[i].clear();
32     edges.clear();
33     memset(vis,0,sizeof(vis));
34 }
35 
36 void addedge(int u,int v,int w)
37 {
38     edges.push_back(edge(u,v,w));
39     edges.push_back(edge(v,u,w));
40     int m=edges.size();
41     G[u].push_back(m-2); 
42     G[v].push_back(m-1);
43 }
44 
45 int dijkstra(int S,int T)
46 {
47     priority_queue<heapnode>q;
48     q.push((heapnode){S,0});
49     for(int i=0;i<m;i++)d[i]=inf;
50     d[S]=0;
51     while(!q.empty())
52     {
53         int u=q.top().u;
54         q.pop();
55         if(vis[u])
56         continue;
57         vis[u]=true;
58         for(int i=0;i<G[u].size();i++)
59         {
60             edge& e=edges[G[u][i]];
61             if(d[e.to]>d[u]+e.dist)
62             {
63                 d[e.to]=d[u]+e.dist;
64                 q.push((heapnode){e.to,d[e.to]});
65             }
66         }
67     }
68     return d[T];
69 }
70 
71 int main()
72 {
73     //freopen("in.txt","r",stdin);
74     int a,b,c,S,T;
75     while(scanf("%d%d",&m,&n)!=EOF)
76     {
77         init();
78         for(int i=0;i<n;i++)
79         {
80             scanf("%d%d%d",&a,&b,&c);
81             addedge(a,b,c);
82         }
83         scanf("%d%d",&S,&T);
84         int ans=dijkstra(S,T);
85         if(ans==inf)
86         printf("-1\n");
87         else
88         printf("%d\n",ans); 
89     }
90     return 0;
91 }

 

posted on 2015-08-11 18:45    阅读(207)  评论(0编辑  收藏  举报

导航