zoukankan      html  css  js  c++  java
  • 最短路径(优先队列优化)

    /*

    O(E*logV)

    */

    #include"cstdio"
    #include"queue"
    #include"algorithm"
    #define INF 1<<28
    #define MAX 300
    using namespace std;
    int v,e,s;
    int graph[MAX][MAX];//图的存储采用邻接矩阵
    int dist[MAX];//dist表示当前距源点最短距离,最终为最短距离
    bool visit[MAX];//标记为已找出最短路径的点
    typedef pair<int,int> P;//用于优先队列中距离与顶点的对应,其中first为距离
    void init()//初始化
    {
        fill(graph[0],graph[0]+MAX*MAX,INF);
        fill(dist,dist+MAX,INF);
        fill(visit,visit+MAX,false);
    }
    void Dijkstra(int s)
    {
        dist[s]=0;
        //优先队列
        priority_queue <P,vector<P>,greater<P> >que;//最后这两个>中间最好加上空格,防止一些编译器识别错误
        que.push(P(0,s));
        while(!que.empty())
        {
            P p=que.top();
            que.pop();
            int vi=p.second;//vi为当前源点编号
            if(visit[vi])
                continue;
            visit[vi]=true;
            for(int i=0;i<v;i++)
            {
                if(!visit[i]&&dist[i]>dist[vi]+graph[i][vi])//查找vi的相邻顶点
                {
                    dist[i]=dist[vi]+graph[i][vi];
                    que.push(P(dist[i],i));
                }
            }
        }
    }
    int main()
    {
        scanf("%d%d%d",&v,&e,&s);
        init();
        for(int i=0;i<e;i++)
        {
            int from,to,cost;
            scanf("%d%d%d",&from,&to,&cost);
            graph[from][to]=graph[to][from]=cost;
        }
        Dijkstra(s);
        for(int i=0;i<v;i++)
        {
            printf("%d %d ",i,dist[i]);
        }
        return 0;
    }

  • 相关阅读:
    C#:反射
    静态和非静态类
    数据的存入取出(注册机方式)
    退出unity运行
    网络流基础
    欧拉回路
    博弈论问题
    洛谷P5304 [GXOI/GZOI2019] 旅行者
    [ZJOI2006]物流运输
    POJ3278 Catch that cow
  • 原文地址:https://www.cnblogs.com/unknownname/p/7792712.html
Copyright © 2011-2022 走看看