zoukankan      html  css  js  c++  java
  • 最短路(模板

    刘汝佳

    #include<cstdio>
    #include<cstring>
    #include<vector>
    #include<algorithm>
    #include<queue>
    using namespace std;
    #define INF 1e8
    const int maxn = 200+10;
    int n,m;
    struct Edge
    {
        int from,to,dist;
        Edge(int f,int t,int d):from(f),to(t),dist(d){}
    };
     
    struct HeapNode
    {
        int d,u;
        HeapNode(int d,int u):d(d),u(u){}
        bool operator< (const HeapNode &rhs)const
        {
            return d > rhs.d;
        }
    };
     
    struct Dijkstra
    {
        int n,m;
        vector<Edge> edges;
        vector<int> G[maxn];
        bool done[maxn];
        int d[maxn];
     
        void init(int n)
        {
            this->n=n;
            for(int i=0;i<n;i++) G[i].clear();
            edges.clear();
        }
     
        void AddEdge(int from,int to,int dist)
        {
            edges.push_back(Edge(from,to,dist));
            m = edges.size();
            G[from].push_back(m-1);
        }
     
        int dijkstra(int s,int e)
        {
            priority_queue<HeapNode> Q;
            for(int i=0;i<n;i++) d[i]=INF;
            d[s]=0;
            Q.push(HeapNode(d[s],s));
            memset(done,0,sizeof(done));
     
            while(!Q.empty())
            {
                HeapNode x= Q.top(); Q.pop();
                int u =x.u;
                if(done[u]) continue;
                done[u]=true;
     
                for(int i=0;i<G[u].size();i++)
                {
                    Edge &e=edges[G[u][i]];
                    if(d[e.to] > d[u]+e.dist)
                    {
                        d[e.to] = d[u]+e.dist;
                        Q.push(HeapNode(d[e.to],e.to));
                    }
                }
            }
            if(d[e] == INF)
                return -1;
            return d[e];
        }
    }DJ;
     
    int main()
    {
        while(scanf("%d%d",&n,&m)==2)
        {
            DJ.init(n);
            for(int i=0;i<m;i++)
            {
                int u,v,d;
                scanf("%d%d%d",&u,&v,&d);
                DJ.AddEdge(u,v,d);
                DJ.AddEdge(v,u,d);
            }
            int s,e;
            scanf("%d%d",&s,&e);
            printf("%d
    ",DJ.dijkstra(s,e) );
        }
        return 0;
    }
    View Code

     第一:建图

    第二:

  • 相关阅读:
    Matlab 图像处理中出现纯黑或纯白是怎么回事?
    网页中的公式在翻译时如何被保留下来?
    请勿 fAKe 评论
    C++ STL 使用注意事项整理
    APIO 2020 题解
    谈谈对题解本质的理解
    点双 & 边双连通图计数的细节比较
    联合省选 2021 A 卷 题解
    指数生成函数(EGF)计数小记
    UOJ-37 清华集训2014 主旋律
  • 原文地址:https://www.cnblogs.com/DWVictor/p/10294696.html
Copyright © 2011-2022 走看看