单源最短路(手写堆+位运算优化+卡常+O2 = Luogu排名最后一页...)

如题

  1 #include<iostream>
  2 #include<cstdio>
  3 #include<cstring>
  4 #include<queue>
  5 #define rep(i,a,n) for(register int i = a;i <= n;++i)
  6 using namespace std;
  7 
  8 void read(int& a){
  9     a = 0;char c = getchar();
 10     while(c < '0'||c > '9')c = getchar();
 11     while('0' <= c&&c <= '9')a = a*10+c-'0',c = getchar();
 12 }
 13 
 14 const int Maxn = 1e5+10,Maxm = 2e5+10; 
 15 
 16 template<typename T>
 17 
 18 void iswap(T &a,T &b){
 19     T t = a;
 20     a = b;
 21     b = t;
 22 }
 23 
 24 template<typename T>
 25 struct Heap{
 26     T a[1000010];int n;
 27     Heap():n(0){}
 28     int size(){return n;}
 29     bool empty(){return !n;}
 30     T top(){return a[1];}
 31     void clear(){n = 0;}
 32     
 33     void push(T x){
 34         a[++n] = x;
 35         int cur = n;
 36         while((cur>>1)&&a[cur>>1] < a[cur])
 37             iswap(a[cur>>1],a[cur]),cur >>= 1;
 38     }
 39     
 40     void pop(){
 41         iswap(a[1],a[n--]);
 42         int cur = 1;
 43         while((cur<<1|1) <= n)
 44             if(a[cur<<1] < a[cur<<1|1]){
 45                 if(a[cur] < a[cur<<1|1]){
 46                     iswap(a[cur],a[cur<<1|1]);
 47                     cur = cur<<1|1;
 48                 }
 49                 else break;
 50             }
 51             else{
 52                 if(a[cur] < a[cur<<1]){
 53                     iswap(a[cur],a[cur<<1]);
 54                     cur <<= 1; 
 55                 } 
 56                 else break;
 57             }
 58         if((cur<<1) <= n&&a[cur] < a[cur<<1])
 59             iswap(a[cur],a[cur<<1]);
 60     }
 61 };
 62 
 63 struct Edge{
 64     int to,wi,ne;
 65 }edges[Maxm];
 66 
 67 int first[Maxn],d[Maxn],vis[Maxn];
 68 int n,m,s,cnte,x,y,z;
 69 
 70 inline void add_edge(int fr,int to,int wi){
 71     edges[++cnte] = (Edge){to,wi,first[fr]};
 72     first[fr] = cnte;
 73 }
 74 
 75 struct Node{
 76     int to,d;
 77     bool operator <(const Node x)const{
 78         return d > x.d;
 79     }
 80 };
 81 
 82 Heap<Node> q;
 83 
 84 inline void dijkstra(int s){
 85     memset(d,0x3f,sizeof(d));
 86     d[s] = 0; q.clear();
 87     q.push((Node){s,0});
 88     while(!q.empty()){
 89         int u = q.top().to; q.pop();
 90         if(vis[u])continue; vis[u] = 1;
 91         for(register int i = first[u];i;i = edges[i].ne){
 92             if(d[edges[i].to] > d[u]+edges[i].wi){
 93                 d[edges[i].to] = d[u]+edges[i].wi;
 94                 q.push((Node){edges[i].to,d[edges[i].to]});
 95             }
 96         }
 97     }
 98 }
 99 
100 int main(){
101     read(n),read(m),read(s);
102     rep(i,1,m){
103         read(x),read(y),read(z);
104         add_edge(x,y,z);
105     }
106     dijkstra(s);
107     rep(i,1,n)printf("%d ",d[i]);
108 return 0;
109 }

 

posted @ 2019-11-07 22:43  TIH_HIT  阅读(205)  评论(0编辑  收藏  举报