zoukankan      html  css  js  c++  java
  • Implementation:Dijkstra

    #include <iostream>
    #include <cstdlib>
    #include <utility>
    #include <queue>
    
    using namespace std;
    
    typedef pair<int, int> P;
    
    int main() {
        // zero means no connection
        int graph[5][5] =   {
                                0, 1, 5, 0, 0,
                                0, 0, 3,10, 9,
                                0, 0, 0, 5, 0,
                                0, 1, 0, 0, 1,
                                0, 0, 0, 0, 0,
                            };
    
        priority_queue<pair<P, P>, vector<P>, greater<P> > que;
    
        vector<int> vd(5, INT_MAX); // min distance from source to each vertex
        que.push(make_pair(0, 0));  // start from 0
        vd[0] = 0;
        
        while (!que.empty()) {
            P cv = que.top();
            que.pop();
            if (cv.second != vd[cv.first]) continue;
            for (int i=0; i<5; i++) {
                if (cv.first == i || graph[cv.first][i] == 0) continue;
                int dst = graph[cv.first][i] + vd[cv.first];
                if (dst < vd[i]) {
                    vd[i] = dst;
                    que.push(make_pair(i, dst));
                }
            }
        }
    
        for (int i=0; i<5; i++)
            cout<<i<<":"<<vd[i]<<endl;
            
        system("pause");
        return 0;
    }

    求单源最短路径,只能处理没有负边的情况,因为它假设每次从上一个最近节点扫描(与它相邻的节点)中都可以获得下一个最近的节点(有负边的话,可能在其他的扫描中该节点可以有更短的距离),这里使用优先队列从候选节点中获得这个最近节点

  • 相关阅读:
    模拟105 题解
    模拟104 题解
    模拟103 题解
    模拟102 题解
    python与 Ajax跨域请求
    Django--进阶--中间件的使用
    Django--权限组件
    python 最基本的的单例模型的实现及应用
    Django-数据库访问优化
    Create views of OpenCASCADE objects in the Debugger
  • 原文地址:https://www.cnblogs.com/lailailai/p/3667134.html
Copyright © 2011-2022 走看看