zoukankan      html  css  js  c++  java
  • dijkstra堆优化模板

     1 #include<iostream>
     2 #include<cmath>
     3 #include<algorithm>
     4 #include<cstring>
     5 #include<cstdio>
     6 #include<queue>
     7 #define inf 2147483647
     8 using namespace std;
     9 struct data
    10 {
    11     int from,to,next,w;
    12     data(){from=-1,to=-1,next=-1,w=-1;}
    13 }e[2000];
    14 struct pa
    15 {
    16     int u,w;
    17     bool operator <(const pa& a)const
    18     {
    19         return w>a.w;
    20     }
    21 };
    22 int n,m;
    23 int head[2000];
    24 int d[2000],p[2000];
    25 bool vis[2000];
    26 int cnt=0;
    27 void add(int u,int v,int w){e[cnt].from=u,e[cnt].to=v;e[cnt].next=head[u],head[u]=cnt,e[cnt].w=w,cnt++;}
    28 void dijkstra(int s)
    29 {
    30     priority_queue<pa> q;
    31     for(int i=1;i<=n;i++) d[i]=inf;
    32     q.push((pa){s,0});
    33     d[s]=0;
    34     memset(vis,0,sizeof(vis));
    35     while(!q.empty())
    36     {
    37         pa x=q.top();
    38         q.pop();
    39         if(vis[x.u]) continue;
    40         vis[x.u]=1;
    41         for(int i=head[x.u];i>=0;i=e[i].next)
    42         {
    43             if(d[e[i].to]>d[e[i].from]+e[i].w)
    44             {
    45                 d[e[i].to]=d[e[i].from]+e[i].w;
    46                 p[e[i].to]=i;
    47                 q.push((pa){e[i].to,d[e[i].to]});
    48             }
    49         }
    50     }
    51 }
    52 int main()
    53 {
    54     memset(head,-1,sizeof(head));
    55     scanf("%d%d",&n,&m);
    56     for(int i=1;i<=m;i++)
    57     {
    58         int u,v,w;
    59         scanf("%d%d%d",&u,&v,&w);
    60         add(u,v,w);
    61         add(v,u,w);
    62     }
    63     int s,t;
    64     scanf("%d%d",&s,&t);
    65     dijkstra(s);
    66     cout<<d[t];
    67 }
    View Code
    O(∩_∩)O~ (*^__^*) 嘻嘻…… O(∩_∩)O哈哈~
  • 相关阅读:
    121. Best Time to Buy and Sell Stock
    分页查询
    ViewPager
    SharedPreferences
    android 动画
    display~
    stringBuffer拼接有规律字符串
    修改placehosder
    this Activity.this Activity.class
    Windows基础编程SDK复习知识点
  • 原文地址:https://www.cnblogs.com/wls001/p/5597165.html
Copyright © 2011-2022 走看看