Dijkstra(邻接表+优先队列)

#include <iostream>

#include<cstdio>

#include<vector>

#include<cstring>

#include<queue>

#include<algorithm>

using namespace std;

typedef pair<int,int>PII;

const int INF=100000;

const int maxn=1000+5;

struct Edge{

int to,weight;

Edge(int to,int weight):to(to),weight(weight) {}

};

int v,e;

int d[maxn];

vector<Edge>G[maxn];

bool done[maxn];

void dijkstra(int start)

{

    memset(done,false,sizeof(done));

    for(int i=1;i<=v;i++)

        d[i]=(i==start?0:INF);

    priority_queue<PII,vector<PII>,greater<PII> >pq;

    pq.push(PII(d[start],start));

    while(!pq.empty())

    {

        PII k=pq.top();

        pq.pop();

        int distance=k.first;

        int vist=k.second;

        if(done[vist]) continue;

        done[vist]=true;

        for(int i=0;i<G[vist].size();i++)

        {

            int k=G[vist][i].to;

            if(d[k]>d[vist]+G[vist][i].weight)

            {

                d[k]=d[vist]+G[vist][i].weight;

                pq.push(PII(d[k],k));

            }

        }

    }

}

int main()

{

    scanf(“%d%d”,&v,&e);

    for(int i=0;i<e;i++)

    {

        int v1,v2,dist;

        scanf(“%d%d%d”,&v1,&v2,&dist);

        /*避免重边*/

        bool flag=false;

        for(int i=0;i<G[v1].size();i++)

        {

            if(G[v1][i].to==v2) {

                                            flag=true;

                                            if(dist<G[v1][i].weight) G[v1][i].weight=dist;

                                            break;

                                         }

        }

        if(!flag) G[v1].push_back(Edge(v2,dist));

    }

    int start,end;

    while(scanf(“%d%d”,&start,&end)==2)

    {

        dijkstra(start);

        if(d[end]>=INF) printf(“No\n”);

        else {

                printf(“Yes\n”);

                printf(“%d\n”,d[end]);

        }

    }

    return 0;

}

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