算法设计,实现有向图的算法

时间:2016-11-06 00:29:09

标签: algorithm graph-theory

我发现这个与算法设计有关的有趣问题,我无法正确解决它。

  

给定有向图G =(V,E),其使用邻接列表,并且整数k <1。 | V |,实现线性时间复杂度算法(O(n)),以检查图形G是否至少具有相同的indegree数的k个顶点。
  假设n == | V | + | E |

1 个答案:

答案 0 :(得分:1)

足以通过所有边,甚至通过所有边节点,并保持所有可能的不确定点的顶点数。

pyhon风格的方法草图:

def check(graph, k):
  # For each vertex count indegree
  indegrees = [0] * graph.number_of_nodes()
  # 'Maps' number of vertices to indegree
  num_with_indegree = [graph.number_of_nodes()] + [0] * (graph.number_of_nodes()-2)
  # Pass through all edge innodes.
  # This iteration is easy to implement with adjancency list graph implementation.
  for in_node in graph.in_nodes():
    # Increase indegree for a node
    indegrees[in_node] += 1
    # 'Move' vertex to it's indegree bucket
    indegree = indegrees[in_node]
    num_with_indegree[indegree-1] -= 1
    num_with_indegree[indegree] += 1
  # Returns true if any bucket has at least k vertices
  return any(n >= k for n in num_with_indegree)