algorithm - 打印每个顶点的入度和出度

标签 algorithm graph graph-theory graph-algorithm directed-graph

我正在为这个算法问题苦苦挣扎:

我将如何编写一个 theta(m+n) 算法来打印 m 边 n 顶点有向图中每个顶点的入度和出度,其中有向图使用邻接表表示。

最佳答案

注意:为简洁起见,我使用“O”代替 theta。

不需要 BFS。

如果您的邻接列表包含有向边列表,请维护两个顶点计数映射,一个用于入度,一个用于出度。每个顶点最初应映射到零。然后遍历每条边 u,v 并递增出度 (u) 和入度 (v)。遍历所有边后,您可以遍历每个顶点,并打印其映射结果。遍历每条边是 O(m),遍历每个顶点(一次初始化映射,一次实际打印它们)是 O(n)。它们的总和是 O(m+n)。

示例代码:

#python-ish, untested

V = set([1,2,3,4,5])
#{(u,v}
E = set([(1,2),(1,3),(2,3)])

in_degree_count = {}
out_degree_count = {}

#initialize the mappings to 0
#O(n)
for u in V:
  in_degree_count[u] = 0
  out_degree_count[u] = 0

#iterate through each edge, incrementing the respective mappings for u,v
#O(m)
for u,v in E:
  out_degree_count[u] += 1
  in_degree_count[v] += 1

#iterate through each vertex to print them
#O(n)
for u in V:
  print 'out_degree({0}):'.format(u), out_degree_count[u]
  print 'in_degree({0}):'.format(u), in_degree_count[u]

您可以为顶点计数映射使用任何关联映射。如果您使用 HashMap ,您将获得摊销的常数时间操作,并且它不会影响整个算法的复杂性。但是,如果您知道顶点在一个没有间隙的范围内,例如 [1,n],那么您可以使用一个计数数组,索引代表具有它的值的顶点。所以:

in_degrees = [0] * (n + 1) #array/list of zeros, of size n,
                           # index 0 is disregarded since there is no vertex named 0
in_degree[1] = 0 # will mean that vertex `1` has an in-degree of zero.
etc.

这显然为您提供了恒定时间映射操作。

关于algorithm - 打印每个顶点的入度和出度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12470989/

相关文章:

r - 如何从同一图上的单个文件中获取多年的 Y 轴数据?

algorithm - 相同长度字符串的最佳字符串匹配算法?

algorithm - 如何用少于 2*n 个字符表示一个 n 字节的数组

javascript - 如何从默认的 highcharts 配置中删除小数点 .00?

Python数据结构 : SQL, XML,或.py文件

python - 所有可能的总和为零的整数集

algorithm - 结合 Dijkstra 算法和 A* 搜索?

arrays - 在 O(n) 时间内检查两个子串是否重叠

database - 多语言持久化关系图数据库是个好主意吗?

c++ - 拓扑排序中的邻接表表示