堆优化的dijstra算法

#include <iostream>
#include <cstdio>
#include <queue>
#include <vector>
#include <cstring>
using namespace std;
const int INF=0x3f3f3f3f;
const int inf=2147483647;
const int maxn=100010;
struct edge
{
    //int from;
    int to;
    int cost;
};
typedef pair<int,int> P;
int V,E;
vector<edge> G[maxn];
int d[maxn];
void dijkstra(int s)
{
    priority_queue<P,vector<P>,greater<P> > q;
    for(int i=0;i<=maxn;i++)
        d[i]=inf;
    //memset(d,127,sizeof(d));
    d[s]=0;
    q.push(P(0,s));
    while(!q.empty())
    {
        P p=q.top();
        q.pop();
        int v=p.second;
        if(d[v]<p.first)
            continue;
        for(int i=0;i<G[v].size();i++)
        {
            edge e=G[v][i];
            if(d[e.to]>d[v]+e.cost)
            {
                d[e.to]=d[v]+e.cost;
                q.push(P(d[e.to],e.to));
            }
        }
    }
}
int main()
{
    int s;
    //点,边,起点
    scanf("%d %d %d",&V,&E,&s);
    for(int i=0;i<E;i++)
    {
        int from,to,cost;
        scanf("%d %d %d",&from,&to,&cost);
        G[from].push_back(edge{to,cost});
    }
    dijkstra(s);
    for(int i=1;i<=V;i++)
    {
        printf("%d ",d[i]);
    }
    printf("\n");
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/zdy1214/p/11396388.html