【发布时间】:2009-09-07 09:39:12
【问题描述】:
我编写了一个算法来计算和存储 DAG 的所有路径,它在小图上运行良好 - 但现在我正在寻求提高它在更大图上运行的效率。该算法的核心逻辑在下面的 createSF() 和 makePathList() 中,其他方法是 helpers - 我可以看到 append 是一个瓶颈。但是,我想最大的帮助是设计一个可以将路径存储在字典中的数据结构,因为许多路径是由其他路径组成的,这是我问题的症结所在。
private Multiset<String> paths = new Multiset<String>();
public Multiset<String> createSF(DAGNode n) {
for (DAGNode succ : n.getSuccessors())
createSF(succ);
if (!n.isVisited())
for (String s : makePathList(n))
paths.put(s);
n.setVisited(true);
return paths;
}
private List<String> makePathList(DAGNode n) {
List<String> list = new ArrayList<String>();
list.add(n.getLabel());
for (DAGNode node : n.getSuccessors())
list.addAll(append(n.getLabel(), makePathList(node)));
return list;
}
private List<String> append(String s, List<String> src) {
List<String> ls = new ArrayList<String>();
for (String str : src)
ls.add(s + "/" + str);
return ls;
}
编辑:
我现在使用一个路径对象来表示路径,并指出了这两种方法的瓶颈:
public List<Path> createPathList(Tree n) {
List<Path> list = new ArrayList<Path>();
list.add(new Path(n.getNodeName()));
for (Tree node : n.getSuccessors()) {
list.addAll(append(n.getNodeName(), createPathList(node)));
}
return list;
}
public List<Path> append(String s, List<Path> src) {
List<Path> ls = new ArrayList<Path>();
for (Path path : src) {
ls.add(new Path(path, s));
}
return ls;
}
问题是当一个图的大小为 M 时,这些方法将被调用 M 次,这意味着这里创建了很多列表...有没有更有效的方法来建立 createPathList() 的返回?
【问题讨论】:
-
你希望用你的路径做什么?为什么将它们中的每一个都存储为一个列表?
标签: java algorithm optimization scalability graph