这是一个使用拓扑排序和动态规划的算法来求解有向无环图(DAG)中从给定源节点到其他节点的最长路径的 C++ 程序。
代码的主要思路如下:
-
定义了一个
AdjListNode
类表示有向图的邻接节点,每个邻接节点包含一个顶点的编号和边的权重。 -
定义了一个
Graph
类表示有向图,使用邻接链表来存储图的结构。 -
使用拓扑排序找到所有顶点的一个线性排列,使得对于图中的每条边 (u, v),u 在拓扑排序中排在 v 的前面。这个排序保证了在动态规划中,我们只会用已经计算出最长路径的顶点来更新其他顶点的最长路径。
-
使用动态规划来计算最长路径。首先初始化一个距离数组
dist
,表示从源节点到其他节点的当前最长距离。将源节点的距离设为 0,其他节点的距离设为负无穷(NINF
)。然后按照拓扑排序的顺序,依次更新每个顶点的最长距离。对于每个顶点 u,遍历其所有邻接节点 v,如果从源节点到 u 的距离加上边权重大于当前已经计算的从源节点到 v 的距离,则更新dist[v]
。 -
输出计算得到的最长距离数组
dist
。
下面对代码进行逐段分析:
// Graph is represented using adjacency list. Every
// node of adjacency list contains vertex number of
// the vertex to which edge connects. It also
// contains weight of the edge
class AdjListNode {
int v;
int weight;
public:
AdjListNode(int _v, int _w)
{
v = _v;
weight = _w;
}
int getV() { return v; }
int getWeight() { return weight; }
};
// Class to represent a graph using adjacency list
// representation
class Graph {
int V; // No. of vertices'
// Pointer to an array containing adjacency lists
list<AdjListNode>* adj;
// A function used by longestPath
void topologicalSortUtil(int v, bool visited[],
stack<int>& Stack);
public:
Graph(int V); // Constructor
~Graph(); // Destructor
// function to add an edge to graph
void addEdge(int u, int v, int weight);
// Finds longest distances from given source vertex
void longestPath(int s);
};
// ...(省略中间部分)
int main()
{
// 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
Graph g(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, 5, 1);
g.addEdge(3, 4, -1);
g.addEdge(4, 5, -2);
int s = 1;
cout << "Following are longest distances from "
"source vertex "
<< s << " \n";
g.longestPath(s);
return 0;
}
这个程序中的图是一个有向无环图(DAG),代码通过拓扑排序来对图进行排序,然后利用动态规划的方法计算从给定源节点到其他节点的最长路径,并输出结果。程序的输出结果将会是:
Following are longest distances from source vertex 1
0 2 6 13 7 9
表示从源节点 1 到其他节点的最长距离依次是:节点 1(源节点)的距离是 0,节点 2 的距离是 2,节点 3 的距离是 6,节点 4 的距离是 13,节点 5 的距离是 7,节点 6 的距离是 9。