algorithm - 有序图伪代码中的最长路径
问题描述
我尝试创建一种算法来找到有序图中的最长路径。有序图的属性是:
- 每条边从索引较低的节点到索引较高的节点。也就是说,每条有向边都具有 i < j 的 (v_i, v_j) 形式。
- 除了 v_n 之外的每个节点都至少有一条边离开它。也就是说,对于每个节点 v_i,至少有一个形式为 (v_i, v_j) 的边。
我的第一次尝试如下:
set w = v1 and L = 0
While there is edge that leaves from w
Choose the edge (w, vj) with j as small as possible
set w = vj and L = L + 1
return L
我不明白为什么这个算法在某些情况下是错误的。你可以给我一个例子吗?
解决方案
我的直觉告诉我,只选择最小的j
并不意味着在其他地方j
将继续是最小的。
假设您有一个图1-> 3
和1 -> 5
,但是3 -> 9
,5 -> 7 -> 9
其中 9 是最后一个节点。你的算法会1 -> 3 -> 9
比1 -> 5 -> 7 -> 9
.
事实上,我不认为你真的可以“挑选”一个分支并继续跟随它到最后并且在任何情况下都是正确的:你必须检查其他分支。
递归方法
这是一种使用简单递归算法的方法,在每个分支处计算路径的长度,然后在有多个分支的节点处返回最长的。
简单的伪代码示例(Python 风格)
class node:
def longest_path(self):
if len(self.children) == 0: # No children in this node
return 1
child_lengths = []
for child in self.children:
child_lengths.append(child.longest_path())
return max(child_lengths) + 1
推荐阅读
- c++ - while(char c=std::cin.get() != 'q') 或 if( char x= c == 'a' || c=='b')
- javascript - 没有从 index.js 调用 nuxtServerInit
- vue.js - 无法理解的“未捕获的 TypeError:无法读取属性 'removeChild' of null”错误
- javascript - 如何根据数据库用户权限在本机反应中从抽屉导航中隐藏菜单?
- emacs - emacs ido-ignore-directories 和 files 不会忽略所有列表
- html - 如何在引导程序 4 中在图像上设置图标位置
- c - 使用 GDB 调试正在运行的守护进程
- mysql - 获取子查询 SQL 的平均值
- pycharm - Pycharm:将光标多行选择作为块
- sql-server - 具有并发控制的存储过程