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

    Code:

    #include<iostream>
    #include<algorithm>
    #include<vector>
    #include<queue>
    #include<cstring>
    #include<cstdio>
    using namespace std;
    const int maxn = 200000;
    const int inf = 2147483647;
    int head[maxn], to[maxn<<1], nex[maxn<<1],val[maxn<<1],cnt;
    struct Node {
        int dist, u;
        Node(int dist, int u) :dist(dist), u(u) {}
        bool operator<(Node v)const {
            return v.dist < dist;
        }
    };
    void addedge(int u,int v,int c){
    	nex[++cnt]=head[u],head[u]=cnt,to[cnt]=v,val[cnt]=c;
    }
    int done[maxn], d[maxn], n, m, s;
    void dijkstra(){
        memset(done, 0, sizeof(done));
        memset(d, 0, sizeof(d));
        priority_queue<Node>Q;
        for (int i = 0; i < maxn; ++i)d[i] = inf;
        d[s] = 0;
        Q.push(Node(0, s));
        while (!Q.empty()) 
        {
            int u = Q.top().u; Q.pop();
            if (done[u])continue;
            done[u] = 1;
            for(int v=head[u];v;v=nex[v]){
            	if(d[u]+val[v]<d[to[v]]){
            		d[to[v]]=d[u]+val[v];
            		Q.push(Node(d[to[v]],to[v]));
            	}
            }
        }
    }
    int main()
    {
    	//freopen("input.in","r",stdin);
        scanf("%d%d%d",&n,&m,&s);
        for(int i=1;i<=m;++i){
        	int a,b,c;
        	scanf("%d%d%d",&a,&b,&c);
        	addedge(a,b,c);
        }
        dijkstra();
        for(int i=1;i<=n;++i) printf("%d ",d[i]);
        return 0;
    }
    

      

  • 相关阅读:
    2017暑期集训Day 1
    17-06-28模拟赛
    17-06-26模拟赛
    平衡树学习笔记
    指针学习笔记
    17-06-14模拟赛
    17-06-11模拟赛
    17-06-02模拟赛
    17-05-31模拟赛
    培训补坑(day1:最短路&two-sat)
  • 原文地址:https://www.cnblogs.com/guangheli/p/9891349.html
Copyright © 2011-2022 走看看