堆优化dijstra


因为spfa没事就被卡一卡,所以堆优化dijstra就显得很重要,在最短路或者其模型里边,最少有一条边是没有被更新过的,也就是它是最短的,同理从这个点开始也有一条边最短,所以每次就找最短的然后松弛操作就可以的。

  1 #include<iostream>
  2 #include<cstdio>
  3 #include<queue>
  4 #include<algorithm>
  5 #include<cmath>
  6 #include<ctime>
  7 #include<set>
  8 #include<map>
  9 #include<stack>
 10 #include<cstring>
 11 #define inf 2147483647
 12 #define ls rt<<1
 13 #define rs rt<<1|1
 14 #define lson ls,nl,mid,l,r
 15 #define rson rs,mid+1,nr,l,r
 16 #define N 200010
 17 #define For(i,a,b) for(register long long i=a;i<=b;i++)
 18 #define p(a) putchar(a)
 19 #define g() getchar()
 20 
 21 using namespace std;
 22 long long n,m,s;
 23 long long x,y,v;
 24 bool vis[N];
 25 
 26 struct node{
 27     long long n;
 28     long long v;
 29     node *next;
 30 }*e[N];
 31 
 32 struct Node
 33 {
 34     long long i;
 35     long long d;
 36     bool operator < (const Node&temp)const{
 37         return d>temp.d;
 38     }
 39 }a[N];
 40 
 41 priority_queue<Node>q;
 42 
 43 void in(long long &x){
 44     long long y=1;
 45     char c=g();x=0;
 46     while(c<'0'||c>'9'){
 47         if(c=='-')y=-1;
 48         c=g();
 49     }
 50     while(c<='9'&&c>='0'){
 51         x=(x<<1)+(x<<3)+c-'0';c=g();
 52     }
 53     x*=y;
 54 }
 55 void o(long long x){
 56     if(x<0){
 57         p('-');
 58         x=-x;
 59     }
 60     if(x>9)o(x/10);
 61     p(x%10+'0');
 62 }
 63 
 64 void push(long long x,long long y,long long v){
 65     node *p;
 66     p=new node();
 67     p->n=y;
 68     p->v=v;
 69     if(e[x]==NULL)
 70         e[x]=p;
 71     else{
 72         p->next=e[x]->next;
 73         e[x]->next=p;
 74     }
 75 }
 76 
 77 void hd(){
 78     a[s].d=0;
 79     q.push(a[s]);
 80     while(!q.empty()){
 81         long long t=q.top().i;
 82         q.pop();
 83         if(vis[t])continue;
 84         vis[t]=true;
 85         for(register node *i=e[t];i;i=i->next){
 86             if(a[t].d+i->v<a[i->n].d){
 87                 a[i->n].d=a[t].d+i->v;
 88                 q.push(a[i->n]);
 89             }
 90         }
 91     }
 92 }
 93 
 94 int main(){
 95     in(n);in(m);in(s);
 96 
 97     For(i,1,m){
 98         in(x);in(y);in(v);
 99         push(x,y,v);
100     }
101 
102     For(i,1,n){
103         a[i].i=i;
104         a[i].d=inf;
105     }
106     hd();
107     For(i,1,n){
108         o(a[i].d);
109         p(' ');
110     }
111     return 0;
112 }
View Code

 !!!!!

它不能处理有负权边,也不能处理最长路!!!!

要牢记啊233333

比如求这个1到2的最短路

posted @ 2019-01-23 11:08  WeiAR  阅读(259)  评论(0编辑  收藏  举报