Given a Weighted Directed Acyclic Graph and a source vertex in the graph, find the shortest paths from given source to all other vertices.
For a general weighted graph, we can calculate single source shortest distances in O(VE) time using Bellman–Ford Algorithm. For a graph with no negative weights, we can do better and calculate single source shortest distances in O(E + VLogV) time using Dijkstra’s algorithm. Can we do even better for Directed Acyclic Graph (DAG)? We can calculate single source shortest distances in O(V+E) time for DAGs. The idea is to use Topological Sorting.

We initialize distances to all vertices as infinite and distance to source as 0, then we find a topological sorting of the graph. Topological Sorting of a graph represents a linear ordering of the graph (See below, figure (b) is a linear representation of figure (a) ). Once we have topological order (or linear representation), we one by one process all vertices in topological order. For every vertex being processed, we update distances of its adjacent using distance of current vertex.

Following figure is taken from this source. It shows step by step process of finding shortest paths.

Following is complete algorithm for finding shortest distances.
1) Initialize dist[] = {INF, INF, ….} and dist[s] = 0 where s is the source vertex.
2) Create a toplogical order of all vertices.
3) Do following for every vertex u in topological order.
………..Do following for every adjacent vertex v of u
………………if (dist[v] > dist[u] + weight(u, v))
………………………dist[v] = dist[u] + weight(u, v)

// Java program to find single source shortest paths in Directed Acyclic Graphs
import java.io.*;
import java.util.*; class ShortestPath
{
static final int INF=Integer.MAX_VALUE;
class AdjListNode
{
private int v;
private int weight;
AdjListNode(int _v, int _w) { v = _v; weight = _w; }
int getV() { return v; }
int getWeight() { return weight; }
} // Class to represent graph as an adjcency list of
// nodes of type AdjListNode
class Graph
{
private int V;
private LinkedList<AdjListNode>adj[];
Graph(int v)
{
V=v;
adj = new LinkedList[V];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList<AdjListNode>();
}
void addEdge(int u, int v, int weight)
{
AdjListNode node = new AdjListNode(v,weight);
adj[u].add(node);// Add v to u's list
} // A recursive function used by shortestPath.
// See below link for details
void topologicalSortUtil(int v, Boolean visited[], Stack stack)
{
// Mark the current node as visited.
visited[v] = true;
Integer i; // Recur for all the vertices adjacent to this vertex
Iterator<AdjListNode> it = adj[v].iterator();
while (it.hasNext())
{
AdjListNode node =it.next();
if (!visited[node.getV()])
topologicalSortUtil(node.getV(), visited, stack);
}
// Push current vertex to stack which stores result
stack.push(new Integer(v));
} // The function to find shortest paths from given vertex. It
// uses recursive topologicalSortUtil() to get topological
// sorting of given graph.
void shortestPath(int s)
{
Stack stack = new Stack();
int dist[] = new int[V]; // Mark all the vertices as not visited
Boolean visited[] = new Boolean[V];
for (int i = 0; i < V; i++)
visited[i] = false; // Call the recursive helper function to store Topological
// Sort starting from all vertices one by one
for (int i = 0; i < V; i++)
if (visited[i] == false)
topologicalSortUtil(i, visited, stack); // Initialize distances to all vertices as infinite and
// distance to source as 0
for (int i = 0; i < V; i++)
dist[i] = INF;
dist[s] = 0; // Process vertices in topological order
while (stack.empty() == false)
{
// Get the next vertex from topological order
int u = (int)stack.pop(); // Update distances of all adjacent vertices
Iterator<AdjListNode> it;
if (dist[u] != INF)
{
it = adj[u].iterator();
while (it.hasNext())
{
AdjListNode i= it.next();
if (dist[i.getV()] > dist[u] + i.getWeight())
dist[i.getV()] = dist[u] + i.getWeight();
}
}
} // Print the calculated shortest distances
for (int i = 0; i < V; i++)
{
if (dist[i] == INF)
System.out.print( "INF ");
else
System.out.print( dist[i] + " ");
}
}
} // Method to create a new graph instance through an object
// of ShortestPath class.
Graph newGraph(int number)
{
return new Graph(number);
} public static void main(String args[])
{
// Create a graph given in the above diagram. Here vertex
// numbers are 0, 1, 2, 3, 4, 5 with following mappings:
// 0=r, 1=s, 2=t, 3=x, 4=y, 5=z
ShortestPath t = new ShortestPath();
Graph g = t.newGraph(6);
g.addEdge(0, 1, 5);
g.addEdge(0, 2, 3);
g.addEdge(1, 3, 6);
g.addEdge(1, 2, 2);
g.addEdge(2, 4, 4);
g.addEdge(2, 5, 2);
g.addEdge(2, 3, 7);
g.addEdge(3, 4, -1);
g.addEdge(4, 5, -2); int s = 1;
System.out.println("Following are shortest distances "+
"from source " + s );
g.shortestPath(s);
}
}

Output:

Following are shortest distances from source 1
INF 0 2 6 5 3

Time Complexity: Time complexity of topological sorting is O(V+E). After finding topological order, the algorithm process all vertices and for every vertex, it runs a loop for all adjacent vertices. Total adjacent vertices in a graph is O(E). So the inner loop runs O(V+E) times. Therefore, overall time complexity of this algorithm is O(V+E).

algorithm@ Shortest Path in Directed Acyclic Graph (O(|V|+|E|) time)的更多相关文章

  1. 拓扑排序-有向无环图(DAG, Directed Acyclic Graph)

    条件: 1.每个顶点出现且只出现一次. 2.若存在一条从顶点 A 到顶点 B 的路径,那么在序列中顶点 A 出现在顶点 B 的前面. 有向无环图(DAG)才有拓扑排序,非DAG图没有拓扑排序一说. 一 ...

  2. AOJ GRL_1_C: All Pairs Shortest Path (Floyd-Warshall算法求任意两点间的最短路径)(Bellman-Ford算法判断负圈)

    题目链接:http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_1_C All Pairs Shortest Path Input ...

  3. AOJ GRL_1_A: Single Source Shortest Path (Dijktra算法求单源最短路径,邻接表)

    题目链接:http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_1_A Single Source Shortest Path In ...

  4. The Shortest Path in Nya Graph

    Problem Description This is a very easy problem, your task is just calculate el camino mas corto en ...

  5. (中等) HDU 4725 The Shortest Path in Nya Graph,Dijkstra+加点。

    Description This is a very easy problem, your task is just calculate el camino mas corto en un grafi ...

  6. HDU 4725 The Shortest Path in Nya Graph (最短路)

    The Shortest Path in Nya Graph Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K ...

  7. Proof for Floyd-Warshall's Shortest Path Derivation Algorithm Also Demonstrates the Hierarchical Path Construction Process

    (THIS BLOG WAS ORIGINALLY WRTITTEN IN CHINESE WITH LINK: http://www.cnblogs.com/waytofall/p/3732920. ...

  8. The Shortest Path in Nya Graph HDU - 4725

    Problem Description This is a very easy problem, your task is just calculate el camino mas corto en ...

  9. HDU 4725 The Shortest Path in Nya Graph(最短路径)(2013 ACM/ICPC Asia Regional Online ―― Warmup2)

    Description This is a very easy problem, your task is just calculate el camino mas corto en un grafi ...

随机推荐

  1. Linux 动画显示

    Linux最强大的一个特征就是它有大量的各种小命令工具,这也可以称做是它最有趣的一个地方了.在这些大量的有用的命令和脚本中,你会发现有少部 分命令工具不那么有用的——如果你不愿意说是完全没用处的话.你 ...

  2. public View getView(int position, View convertView, final ViewGroup parent)三个参数的意思

    最近看到有人在问这三个参数的含义,其实帮助已经很详细的介绍了这三个参数,看来还是要好好学学英语了,不然连解释都看不懂. /**     * Get a View that displays the d ...

  3. ios中addtarget

    Target-action:目标-动作模式,它贯穿于iOS开发始终.但是对于初学者来说,还是被这种模式搞得一头雾水. 其实Target-action模式很简单,就是当某个事件发生时,调用那个对象中的那 ...

  4. NDK(16)Jni中GetStaticFieldID和GetMethodID 中的类型标识串

    env在GetStaticFieldID和GetMethodID 时,函数参数和返回值的类型要指定类型标识串,如: jmethodID init = env->GetMethodID(clz,& ...

  5. ASP.NET MVC 学习5、登陆页面改为SSO验证

    单点登录(SSO,single sign-on)是一个会话或用户身份验证过程,用户只需要登录一次就可以访问所有相互信任的应用系统,二次登录时无需重新输入用户名和密码.简化账号登录过程并保护账号和密码安 ...

  6. C#手动回收内存的简单方法

    C#有自动回收内存的机制,但是有时自动回收有一定滞后,需要在变量使用后迅速回收,节约内存,这里介绍一个最简单的方法. 1.先对对象赋值 null; 2.System.GC.Collect(); 代码样 ...

  7. uva 10047 The Monocycle(搜索)

    好复杂的样子..其实就是纸老虎,多了方向.颜色两个状态罢了,依旧是bfs. 更新的时候注意处理好就行了,vis[][][][]要勇敢地开. 不过这个代码交了十几遍的submission error,手 ...

  8. noip2007提高组题解

    题外话:这一年的noip应该是最受大众关心的,以至于在百度上输入noip第三个关键字就是noip2007.主要是由于这篇文章:http://www.zhihu.com/question/2110727 ...

  9. DataGuard相同SID物理Standby搭建

    Oracle Data Guard 是针对企业数据库的最有效和最全面的数据可用性.数据保护和灾难恢复解决方案.它提供管理.监视和自动化软件基础架构来创建和维护一个或多个同步备用数据库,从而保护数据不受 ...

  10. Oracle中HWM与数据库性能的探讨

    Oracle中HWM与数据库性能的探讨 一.什么是高水位 HWM(high water mark),高水标记,这个概念在segment的存储内容中是比较重要的.简单来说,HWM就是一个segment中 ...