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;
}

  

   
上一篇:GMOJ 6683. 我图呢 题解


下一篇:(UVA - 11584) Partitioning by Palindromes(DP,划分的最小回文串个数)