加权有向无环图中的最长路径使用 R igraph

3
我使用R igraph实现了加权DAG的最长路径计算。但是,我的实现(如下所示)对于大型图形来说速度较慢。我非常感谢任何可以加速它的提示。如果您对最佳已知/典型算法有任何想法,也欢迎分享。谢谢!
# g is the igraph DAG
# g <- graph.tree(10000, 2, mode="out")
# E(g)$weight <- round(runif(length(E(g))),2) * 50 
# Topological sort
tsg <- topological.sort(g)    
# Set root path attributes
# Root distance
V(g)[tsg[1]]$rdist <- 0
# Path to root
V(g)[tsg[1]]$rpath <- tsg[1]
# Get longest path from root to every node        
for(node in tsg[-1])
{
  # Get distance from node's predecessors
  w <- E(g)[to(node)]$weight
  # Get distance from root to node's predecessors
  d <- V(g)[nei(node,mode="in")]$rdist
  # Add distances (assuming one-one corr.)
  wd <- w+d
  # Set node's distance from root to max of added distances 
  mwd <- max(wd)
  V(g)[node]$rdist <- mwd
  # Set node's path from root to path of max of added distances
  mwdn <- as.vector(V(g)[nei(node,mode="in")])[match(mwd,wd)]
  V(g)[node]$rpath <- list(c(unlist(V(g)[mwdn]$rpath), node))      
}
# Longest path length is the largest distance from root
lpl <- max(V(g)$rdist)    
# Enumerate longest path
lpm <- unlist(V(g)[match(lpl,V(g)$rdist)]$rpath)    
V(g)$critical <- 0
g <- set.vertex.attribute(g, name="critical", index=lpm, value=1)    

分析代码以查看哪里有问题。查看Rprof()函数。 - Gabor Csardi
1个回答

2
我之前的 R 版本运行缓慢,处理 20 万条边和 3 万个顶点需要约 20 分钟。于是我决定实现带有负权边的图的 get.shortest.paths(),你可以通过反转所有边的权重来找到最长路径。你可以在这里尝试我的 R 的分支版本 igraph here
当我从 R 切换到 C 后,我经历了 100 倍至 1000 倍的加速。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接