Shirlies
宁静专注认真的程序媛~

最短路Dijkstra算法,用优先队列。。。

代码如下:
 1 #include <cstdio>
 2 #include <cstring>
 3 #include <queue>
 4 #include <vector>
 5 using namespace std;
 6 
 7 const int maxn = 50010;
 8 struct node
 9 {
10     int v;
11     int w;
12 };
13 
14 typedef pair<int,int> pii;
15 vector<node> p[2*maxn];
16 int  n,m;
17 int S,T;
18 int d[20020];
19 
20 void solve()
21 {
22     memset(d,-1,sizeof(d));
23     priority_queue<pii,vector<pii>,greater<pii> > q;
24     d[S] = 0;
25     q.push(make_pair(d[S],S));
26     while(!q.empty())
27     {
28         pii u = q.top();
29         q.pop();
30         int x = u.second;
31         if(u.first != d[x])
32             continue;
33         int len = p[x].size();
34         for(int i = 0;i < len ;i ++)
35         {
36             if(d[p[x].at(i).v] == -1)
37             {
38                 d[p[x].at(i).v] = d[x] +p[x].at(i).w;
39                 q.push(make_pair(d[p[x].at(i).v],p[x].at(i).v));
40             }
41             else if(d[p[x].at(i).v] > d[x] + p[x].at(i).w)
42             {
43                 d[p[x].at(i).v] = d[x] + p[x].at(i).w;
44                 q.push(make_pair(d[p[x].at(i).v],p[x].at(i).v));
45             }
46         }
47     }
48 }
49 int main()
50 {
51     int cas = 1;
52     int N;
53     scanf("%d",&N);
54     while(N --)
55     {
56         scanf("%d%d%d%d",&n,&m,&S,&T);
57         for(int i = 0;i < 2 *maxn;i ++)
58         {
59             p[i].clear();
60         }
61         for(int i = 0;i < m;i ++)
62         {
63             int a,b,w;
64             scanf("%d%d%d",&a,&b,&w);
65             node temp;
66             temp.v = b;
67             temp.w = w;
68             p[a].push_back(temp);
69             temp.v = a;
70             p[b].push_back(temp);
71         }
72 
73         solve();
74         printf("Case #%d: ",cas ++);
75         if(d[T] == -1)
76         {
77             printf("unreachable\n");
78         }
79         else
80         {
81             printf("%d\n",d[T]);
82         }
83     }
84 
85     return 0;
86 }

 

posted on 2012-04-18 17:14  Shirlies  阅读(356)  评论(0编辑  收藏  举报