让说,我有其中的节点存储在一个排序列表的图。 我现在要拓扑排序这个图,同时保持在拓扑顺序是未定义的原始顺序。 有没有这方面的任何好的算法?
Answer 1:
一种可能性是计算字典序至少拓扑顺序。 该算法是保持含有其有效入度(超过节点尚未处理)为零的节点一个优先级队列。 多次出队用最少的标签的节点,其追加的顺序,递减有效度的继任者,入队,现在有度为零的人。 这将产生对btilly的例子1234567890,但一般不减少倒置。
我喜欢这个算法的性能,输出有一个干净的定义中,只有一个订单明显感到满意,并认为,只要有一个反转(节点Y之后节点X出现,即使X <Y),X的最大依赖于Y最大的大依赖,这是颠倒X和Y的各种“借口”。 的必然结果是,在没有约束的,该法至少顺序是排序顺序。
Answer 2:
这个问题有两方面:
- 拓扑排序
- 稳定排序
许多错误和审判后,我想出了一个简单的算法类似冒泡排序但拓扑排序标准。
我彻底的测试算法与完整的边缘组合将全部图形,因此它可以作为证明予以考虑。
循环依赖根据在序列元素的原始顺序的耐受性和解决。 排序结果是完美的,代表了最接近的匹配。
下面是C#的源代码:
static class TopologicalSort
{
/// <summary>
/// Delegate definition for dependency function.
/// </summary>
/// <typeparam name="T">The type.</typeparam>
/// <param name="a">The A.</param>
/// <param name="b">The B.</param>
/// <returns>
/// Returns <c>true</c> when A depends on B. Otherwise, <c>false</c>.
/// </returns>
public delegate bool TopologicalDependencyFunction<in T>(T a, T b);
/// <summary>
/// Sorts the elements of a sequence in dependency order according to comparison function with Gapotchenko algorithm.
/// The sort is stable. Cyclic dependencies are tolerated and resolved according to original order of elements in sequence.
/// </summary>
/// <typeparam name="T">The type of the elements of source.</typeparam>
/// <param name="source">A sequence of values to order.</param>
/// <param name="dependencyFunction">The dependency function.</param>
/// <param name="equalityComparer">The equality comparer.</param>
/// <returns>The ordered sequence.</returns>
public static IEnumerable<T> StableOrder<T>(
IEnumerable<T> source,
TopologicalDependencyFunction<T> dependencyFunction,
IEqualityComparer<T> equalityComparer)
{
if (source == null)
throw new ArgumentNullException("source");
if (dependencyFunction == null)
throw new ArgumentNullException("dependencyFunction");
if (equalityComparer == null)
throw new ArgumentNullException("equalityComparer");
var graph = DependencyGraph<T>.TryCreate(source, dependencyFunction, equalityComparer);
if (graph == null)
return source;
var list = source.ToList();
int n = list.Count;
Restart:
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < i; ++j)
{
if (graph.DoesXHaveDirectDependencyOnY(list[j], list[i]))
{
bool jOnI = graph.DoesXHaveTransientDependencyOnY(list[j], list[i]);
bool iOnJ = graph.DoesXHaveTransientDependencyOnY(list[i], list[j]);
bool circularDependency = jOnI && iOnJ;
if (!circularDependency)
{
var t = list[i];
list.RemoveAt(i);
list.Insert(j, t);
goto Restart;
}
}
}
}
return list;
}
/// <summary>
/// Sorts the elements of a sequence in dependency order according to comparison function with Gapotchenko algorithm.
/// The sort is stable. Cyclic dependencies are tolerated and resolved according to original order of elements in sequence.
/// </summary>
/// <typeparam name="T">The type of the elements of source.</typeparam>
/// <param name="source">A sequence of values to order.</param>
/// <param name="dependencyFunction">The dependency function.</param>
/// <returns>The ordered sequence.</returns>
public static IEnumerable<T> StableOrder<T>(
IEnumerable<T> source,
TopologicalDependencyFunction<T> dependencyFunction)
{
return StableOrder(source, dependencyFunction, EqualityComparer<T>.Default);
}
sealed class DependencyGraph<T>
{
private DependencyGraph()
{
}
public IEqualityComparer<T> EqualityComparer
{
get;
private set;
}
public sealed class Node
{
public int Position
{
get;
set;
}
List<T> _Children = new List<T>();
public IList<T> Children
{
get
{
return _Children;
}
}
}
public IDictionary<T, Node> Nodes
{
get;
private set;
}
public static DependencyGraph<T> TryCreate(
IEnumerable<T> source,
TopologicalDependencyFunction<T> dependencyFunction,
IEqualityComparer<T> equalityComparer)
{
var list = source as IList<T>;
if (list == null)
list = source.ToArray();
int n = list.Count;
if (n < 2)
return null;
var graph = new DependencyGraph<T>();
graph.EqualityComparer = equalityComparer;
graph.Nodes = new Dictionary<T, Node>(n, equalityComparer);
bool hasDependencies = false;
for (int position = 0; position < n; ++position)
{
var element = list[position];
Node node;
if (!graph.Nodes.TryGetValue(element, out node))
{
node = new Node();
node.Position = position;
graph.Nodes.Add(element, node);
}
foreach (var anotherElement in list)
{
if (equalityComparer.Equals(element, anotherElement))
continue;
if (dependencyFunction(element, anotherElement))
{
node.Children.Add(anotherElement);
hasDependencies = true;
}
}
}
if (!hasDependencies)
return null;
return graph;
}
public bool DoesXHaveDirectDependencyOnY(T x, T y)
{
Node node;
if (Nodes.TryGetValue(x, out node))
{
if (node.Children.Contains(y, EqualityComparer))
return true;
}
return false;
}
sealed class DependencyTraverser
{
public DependencyTraverser(DependencyGraph<T> graph)
{
_Graph = graph;
_VisitedNodes = new HashSet<T>(graph.EqualityComparer);
}
DependencyGraph<T> _Graph;
HashSet<T> _VisitedNodes;
public bool DoesXHaveTransientDependencyOnY(T x, T y)
{
if (!_VisitedNodes.Add(x))
return false;
Node node;
if (_Graph.Nodes.TryGetValue(x, out node))
{
if (node.Children.Contains(y, _Graph.EqualityComparer))
return true;
foreach (var i in node.Children)
{
if (DoesXHaveTransientDependencyOnY(i, y))
return true;
}
}
return false;
}
}
public bool DoesXHaveTransientDependencyOnY(T x, T y)
{
var traverser = new DependencyTraverser(this);
return traverser.DoesXHaveTransientDependencyOnY(x, y);
}
}
}
和一个小示例应用程序:
class Program
{
static bool DependencyFunction(char a, char b)
{
switch (a + " depends on " + b)
{
case "A depends on B":
return true;
case "B depends on D":
return true;
default:
return false;
}
}
static void Main(string[] args)
{
var source = "ABCDEF";
var result = TopologicalSort.StableOrder(source.ToCharArray(), DependencyFunction);
Console.WriteLine(string.Concat(result));
}
}
给定了输入的元素{A,B,C,d,E,F},其中A依赖于B和B取决于d的输出为{d,B,A,C,E,F}。
更新:我写了一篇小文章有关稳定拓扑排序目标,算法及打样。 希望这给更多的解释和对开发人员和研究人员非常有用。
Answer 3:
您没有足够的条件来指定你在找什么。 例如考虑有两个向器件的图形。
1 -> 2 -> 3 -> 4 -> 5
6 -> 7 -> 8 -> 9 -> 0
你更喜欢以下哪个种类的?
6, 7, 8, 9, 0, 1, 2, 3, 4, 5
1, 2, 3, 4, 5, 6, 7, 8, 9, 0
从打破通过将最低节点尽量靠近列表尽可能的头部一切关系的第一个成果。 因此0胜。 从试图最小化A <B和B在拓扑排序A之前出现的次数的第二结果。 两者都是合理的答案。 第二个可能是更加赏心悦目。
我可以很容易地生产的第一种算法。 首先,拿最低的节点,并做了广度优先搜索来定位,以最短的根节点的距离。 如果有一条领带,确定一系列可能出现这样的最短路径上的节点。 参加该组最低的节点,并从它的最佳路径到根目录,然后把从我们开始给它的最低点的最佳路径。 搜索,是不是已经在拓扑排序的下一个最低点,然后继续。
生产用于更赏心悦目版本的算法似乎更难。 见http://en.wikipedia.org/wiki/Feedback_arc_set对于相关的问题有力地表明,它是,事实上,NP完全问题。
Answer 4:
下面是一个简单的迭代的方法进行拓扑排序:不断地删除一个节点,在度0,连同其边缘。
为了获得一个稳定的版本,只需修改到:不断地除去最小的索引节点度0,连同其边缘。
在伪蟒蛇:
# N is the number of nodes, labeled 0..N-1
# edges[i] is a list of nodes j, corresponding to edges (i, j)
inDegree = [0] * N
for i in range(N):
for j in edges[i]:
inDegree[j] += 1
# Now we maintain a "frontier" of in-degree 0 nodes.
# We take the smallest one until the frontier is exhausted.
# Note: You could use a priority queue / heap instead of a list,
# giving O(NlogN) runtime. This naive implementation is
# O(N^2) worst-case (when the order is very ambiguous).
frontier = []
for i in range(N):
if inDegree[i] == 0:
frontier.append(i)
order = []
while frontier:
i = min(frontier)
frontier.remove(i)
for j in edges[i]:
inDegree[j] -= 1
if inDegree[j] == 0:
frontier.append(j)
# Done - order is now a list of the nodes in topological order,
# with ties broken by original order in the list.
Answer 5:
解读“稳定拓扑排序”为这样的DAG范围下的线性化在拓扑顺序并不重要的线性化,是字典序排序。 这可以用来解决DFS线性化的方法,与该节点在词典编纂顺序访问的修改。
我有一个看起来像这样的线性化方法一个Python有向图类:
def linearize_as_needed(self):
if self.islinearized:
return
# Algorithm: DFS Topological sort
# https://en.wikipedia.org/wiki/Topological_sorting#Depth-first_search
temporary = set()
permanent = set()
L = [ ]
def visit(vertices):
for vertex in sorted(vertices, reverse=True):
if vertex in permanent:
pass
elif vertex in temporary:
raise NotADAG
else:
temporary.add(vertex)
if vertex in self.arrows:
visit(self.arrows[vertex])
L.append(vertex)
temporary.remove(vertex)
permanent.add(vertex)
# print('visit: {} => {}'.format(vertices, L))
visit(self.vertices)
self._linear = list(reversed(L))
self._iter = iter(self._linear)
self.islinearized = True
这里
self.vertices
是集所有顶点,并
self.arrows
持有的邻接关系为左节点来套左右节点的字典。
Answer 6:
在Wikipedia上的深度优先搜索算法的工作对我来说:
const assert = chai.assert; const stableTopologicalSort = ({ edges, nodes }) => { // https://en.wikipedia.org/wiki/Topological_sorting#Depth-first_search const result = []; const marks = new Map(); const visit = node => { if (marks.get(node) !== `permanent`) { assert.notEqual(marks.get(node), `temporary`, `not a DAG`); marks.set(node, `temporary`); edges.filter(([, to]) => to === node).forEach(([from]) => visit(from)); marks.set(node, `permanent`); result.push(node); } }; nodes.forEach(visit); return result; }; const graph = { edges: [ [5, 11], [7, 11], [3, 8], [11, 2], [11, 9], [11, 10], [8, 9], [3, 10] ], nodes: [2, 3, 5, 7, 8, 9, 10, 11] }; assert.deepEqual(stableTopologicalSort(graph), [5, 7, 11, 2, 3, 8, 9, 10]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/4.2.0/chai.min.js"></script>