• 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 }
  • 相关阅读:
    计算机执行程序代码的过程分析
    iOS 操作系统架构
    ios 概况了解
    android ApplicationContext Context Activity 内存的一些学习
    android 内存优化一
    android 学习
    ios 基础学习二
    ios 集合总结
    线程之间的通讯---SynchronizationContext
    ASP.NET Core 身份验证及鉴权
  • 原文地址:https://www.cnblogs.com/Shirlies/p/2455613.html
Copyright © 2020-2023  润新知