问题是
Given a graph and N sets of vertices, how to check that if the vertices
in each set exist on a path (that may not have to be simple) in the
graph.
例如,如果一组顶点是{A,B,C}
1) On a graph
A --> B --> C
The vertices A, B and C are on a path
2) On a graph
A ---> B ---> ...
^
C -----+
The vertices A, B and C are not on a path
3) On a graph
A <--- B <--- ...
|
C <----+
The vertices A, B and C are not on a path
4) On a graph
A ---> X -----> B ---> C --> ...
| ^
+---------------+
The vertices A, B and C are on a path
这是一个复杂度为N *(V + E)的简单算法。
for each set S of vertices with more than 1 elements {
initialize M that maps a vertice to another vertice it reaches;
mark all vertices of G unvisited;
pick and remove a vertex v from S;
while S is not empty {
from all unvisited node, find one vertex v' in S that v can reach;
if v' does not exist {
pick and remove a vertex v from S;
continue;
}
M[v] = v';
remove v' from S;
v = v';
}
// Check that the relations in M forms a path
{
if size[M] != size(S)-1 {
return false;
}
take the vertex v in S that is not in M
while M is not empty {
if not exist v' s.t. M[v]' = v {
return false;
}
}
return true;
}
}
for循环需要N步; while-loop将以最坏的情况访问所有节点/边缘,成本为V + E.
是否有任何已知算法可以解决问题? 如果图表是DAG,我们可以有更好的解决方案吗?
谢谢
答案 0 :(得分:1)
这里的无关不是一个有意义的假设,因为我们可以将每个强组件合并到一个顶点。路径也是红鲱鱼;通过一堆双节点路径,我们实际上在DAG中进行了一系列可达性查询。比O(n 2 )更快地执行此操作被认为是一个难题:https://cstheory.stackexchange.com/questions/25298/dag-reachability-with-on-log-n-space-and-olog-n-time-queries。
答案 1 :(得分:1)
您应该查看Floyd-Warshall algorithm。它将为您提供O(V 3 )图中所有顶点对之间最短路径的长度。获得这些结果后,您可以进行强力深度优先遍历,以确定是否可以从一个节点转到下一个节点以及下一个节点等。这应该在O(n n )中发生其中n是当前集合中的顶点数。那么,总复杂度应该是O(V 3 + N * n n )(或类似的东西)。
n n 似乎令人生畏,但如果n与V相比较小,那么在实践中它将不是一件大事。
我可以猜测,鉴于图表上的某些限制,人们可以改进。