uva 10986

最短路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 }

 

转载于:https://www.cnblogs.com/Shirlies/archive/2012/04/18/2455613.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值