美文网首页
求有向图的最短路径

求有向图的最短路径

作者: 黑山老水 | 来源:发表于2018-01-28 14:33 被阅读19次

Description:

Find the minimum cost to reach destination using a train
There are N stations on route of a train. The train goes from station 0 to N-1. The ticket cost for
all pair of stations (i, j) is given where j is greater than i. Find the minimum cost to reach the
destination.

Example:

Input:
cost[N][N] = { {0, 15, 80, 90},
{INF, 0, 40, 50},
{INF, INF, 0, 70},
{INF, INF, INF, 0}
};
There are 4 stations and cost[i][j] indicates cost to reach j
from i. The entries where j < i are meaningless.
Output:
The minimum cost is 65

完整代码:

//Q5
//we can use Dijkstra algorithm to solve this problem
//the time complexity will be O(N^2) where N is the number of stations
//if we can use Fibonacci heap for this case, the running time will be down to O(E + NlogN)
//but STL doesn't include any implementation for Fibonacci heap (boost may have)
//so we wouldn't use normal heap sort, otherwise, the running time will up to O(N^2 * logN)
int minimumCost(int n, vector<vector<int>>& cost) {
    vector<int> weights;
    unordered_set<int> unCheck;
    for(int i = 0; i < n; i++) {
        if(i == 0)
            weights.push_back(0);
        else 
            weights.push_back(INT_MAX);
        unCheck.insert(i);
    }
    while(!unCheck.empty()) {
        //we use a scan to find out the heap top instead of use heap sort
        int minWeight = INT_MAX;
        int next;
        for(int i: unCheck) {
            if(weights[i] < minWeight) {
                minWeight = weights[i];
                next = i;
            }
        }
        //remove node from set
        unCheck.erase(next);
        //update weights
        for(int i = next; i < n; i++) {
            weights[i] = min(weights[i], weights[next] + cost[next][i]);
        }
    }
    return weights[n - 1];
}

相关文章

  • java最短路径(jgrapht)

    基于jgrapht求最短路径的算法,有向图/无向图,加权图

  • 最短路径

    无权图的最短路径用BFS来求 O(|V|+|E|) 有向带权图两点之间的最短路径也包含了路径上其他顶点间的最短路径...

  • 求有向图的最短路径

    Description: Find the minimum cost to reach destination u...

  • 《算法》笔记 12 - 最短路径

    加权有向图 数据结构加权有向边加权有向图最短路径 边的松弛 Dijkstra算法 地图或者导航系统是最短路径的典型...

  • 19-最短路径(Shortest Path)

    最短路径(Shortest Path) 最短路径是指两个顶点之间权值之和最小的路径(有向图,无向图均可,不能有负权...

  • 队列Queue--最短路径数

    给定如图所示的无向连通图,假定图中所有边权都为1,显然,从源点A到终点T的最短路径有多条,求不同的最短路径数目。 ...

  • NetworksX 图 使用

    1.有向图 2.无向图 3.节点颜色图 计算:计算1:求无向图的任意两点间的最短路径 结果 计算2:求出有向图中得...

  • 有向图和最短路径Dijkstra、Bellman-Ford、Fl

    本篇开始讨论关于有向图的算法,无向图是特殊的有向图。内容概要: 有向图的实现 最短路径经典算法实现 有向图的实现 ...

  • dijkstra(狄克斯特拉)算法

    dijkstra是用来求最短路径的一种算法,能得出最优解,属于广度优先搜索法 思路分解 图1表示一个有向,有权图 ...

  • 静态寻路算法Dijkstra(python)

    算法介绍 迪科斯彻算法使用了广度优先搜索解决赋权有向图或者无向图的单源最短路径问题,算法最终得到一个最短路径树。该...

网友评论

      本文标题:求有向图的最短路径

      本文链接:https://www.haomeiwen.com/subject/hoaaaxtx.html