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)    
4

1 回答 1

1

我也有一个慢速的 R 版本。200k 边和 30k 顶点大约需要 20 分钟,所以我分解并实现get.shortest.paths()了具有负边权重的图,您可以通过反转所有边权重来找到最长路径。igraph 你可以在这里试试我的 R 叉。

从我的 R 实现切换到 C 时,我经历了 100 倍到 1000 倍的加速。

于 2015-03-22T23:37:50.323 回答