• Dijkstra模板 dj斯特拉


    图论里非常常用的dijkstra,自己加了个路径查找,做个模板吧:

    int maxn = 100005;
    struct Edge {
        int from,to,dist;
        Edge(int u, int v, int d):from(u),to(v),dist(d)  {}
    };
    struct HeapNode {
        int d,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];
        int p[maxn];     //最短路中的上一条弧
        vector<int> path;
        void init(int n) {
            this->n = n;
            for (int i = 0; i < n; i++) G[i].clear();
            edges.clear();
            path.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);
        }
    
        void dijkstra(int s) {    //从s点开始
            priority_queue<HeapNode> Q;
            for (int i = 0; i < n; i++) d[i] = INF;
            d[s] = 0;
            memset(done,0,sizeof(done));
            Q.push((HeapNode) {
                0,s
            });
            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;
                        p[e.to] = G[u][i];
                        Q.push((HeapNode) {
                            d[e.to],e.to
                        });
                    }
                }
            }
        }
        void findpath(int x,int end) {
            path.clear();
            path.push_back(x);
            findd(x,end);
        }
        void findd(int x,int end) {
            if(x==end)
                return;
            else {
                path.push_back(this->edges[this->p[x]].from);
                findd(this->edges[this->p[x]].from,end);
            }
        }
    };
  • 相关阅读:
    民宿项目知识_服务器路径与文件的存储
    民宿项目_mysql_jdbc
    Apple Mach-O Linker Warning
    ios控制器视图载入周期小记
    StatusBar style的那点事
    oc--单例设计模式
    gcd笔记
    【转载】10年的程序员生涯(附带原文地址)
    NSProxy使用笔记
    UINavigationController的视图层理关系
  • 原文地址:https://www.cnblogs.com/zinyy/p/9139099.html
Copyright © 2020-2023  润新知