(模板) Dijkstra算法(priority_queue优化)

写法1,利用struct存当前最近点的信息:

#include<cstdio>
#include<iostream>
#include<vector>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
struct edge{
    int to,cost;
};
vector<edge>G[10005];
struct d{//记录各种被松弛后的点
    int num,dis;
};
bool operator <(d a,d b)
{
    return a.dis>b.dis;
}
int main()
{
    int n,m,s,i,j,k;
    cin>>n>>m>>s;
    for(i=1;i<=m;i++){
        int a,b,c;
        scanf("%d %d %d",&a,&b,&c);
        G[a].push_back(edge{b,c});
    }
    int dis[10005];memset(dis,0x7f,sizeof(dis));dis[s]=0;
    priority_queue<d>que;
    que.push(d{s,0});
    while(!que.empty()){
        d e=que.top();que.pop();
        if(e.dis>dis[e.num])continue;//这里也可以利用一个额外的数组来保证每个点只被访
        //问一次,或者说最短距离已经确定的点不再被更改
        for(int i=0;i<G[e.num].size();i++){
            edge eg=G[e.num][i];
            if(dis[eg.to]>dis[e.num]+eg.cost){
                dis[eg.to]=dis[e.num]+eg.cost;
                que.push(d{eg.to,dis[eg.to]});
            }
        }
    }
    for(i=1;i<=n;i++)
        if(dis[i]==dis[10004])cout<<2147483647<<' ';
        else cout<<dis[i]<<' ';

    return 0;
}

写法2,使用pair和functional:

#include<cstdio>
#include<vector>
#include<queue>
#include<algorithm>
#include<functional>
using namespace std;
typedef struct {
    int to, cost;
}Edge;
vector<Edge>edge[10001];
typedef pair<int, int>P;
priority_queue<P, vector<P>, greater<P> >q;
int book[10001], dis[10001];
int main(void)
{
    int n, m, s, i, j;

    scanf("%d %d %d", &n, &m, &s);
    fill(dis, dis + n+1, 2147483647); dis[s] = 0;
    for (i = 1; i <= m; i++) {
        int a, b, c;
        scanf("%d %d %d", &a, &b, &c);
        Edge temp;
        temp.to = b; temp.cost = c;
        edge[a].push_back(temp);
    }
    P p; p.first = 0; p.second = s; q.push(p);
    while (!q.empty()) {
        P p = q.top(); q.pop();
        if (book[p.second] == 1) continue;
        book[p.second] = 1;
        for (i = 0; i < edge[p.second].size(); i++) {
            Edge temp = edge[p.second][i];
            if (dis[temp.to] > dis[p.second] + temp.cost) {
                dis[temp.to] = dis[p.second] + temp.cost;
                P p1; p1.first = dis[temp.to]; p1.second = temp.to;
                q.push(p1);
            }
        }
    }
    for (i = 1; i < n; i++)
        printf("%d ", dis[i]);
    printf("%d\n", dis[n]);

    return 0;
}
    原文作者:Dijkstra算法
    原文地址: https://blog.csdn.net/HumveeA6/article/details/79435243
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞