Python
author:zoxiii
题目
用n表示结点的个数,
a
n
a_n
an表示有
n
n
n个结点的有向无环图个数。则有下面递推公式成立:
a
n
=
∑
i
=
1
n
(
−
1
)
i
+
1
2
(
n
−
i
)
i
(
n
i
)
a
n
−
i
a_n=\sum_{i=1}^n {(-1)}^{i+1}2^{(n-i)i}{n \choose i}a_{n-i}
an=i=1∑n(−1)i+12(n−i)i(in)an−i
- 编辑一个函数,计算 a n a_n an。
- 并且计算 a n , n = 10 , 20 , ⋯ , 100 a_{n},n=10,20,\cdots,100 an,n=10,20,⋯,100。
解答
查阅资料:
- 零图:顶点集V和边集E都为空的图
- 有向无环图可以有孤立结点存在
编写函数
import numpy as np
from scipy.special import comb
## n:节点个数
## an:有向无环图个数
def count_an(n):
"""count the num of DAG for n nodes"""
if n == 0:
an = 1
else:
an = 0
for i in range(1,n+1):
temp1 = (-1)**(i+1)
temp2 = 2**((n-i)*i)
temp3 = comb(n,i)
an += temp1*temp2*temp3*count_an(n-i)
return int(an)
计算
print("n\tan")
for m in range(0,20,1): ##(10,101,10)
print("%d\t%d"%(m,count_an(m)))
问题
- 计算速度慢
- 结果溢出
一点改进:递归时存储已计算的值,增快计算速度
from scipy.special import comb
import numpy as np
## n:节点个数
## an:有向无环图个数
def count_an(n,an):
"""count the num of DAG for n nodes"""
if n == 0:
an[n] = 1
else:
for i in range(1,n+1):
if an[n-i] == 0:
an[n-i] = count_an(n-i,an)
#temp1 = (-1)**(i+1)
#temp2 = 2**((n-i)*i)
#temp3 = comb(n,i)
an[n] += (-1)**(i+1) * 2**((n-i)*i) * comb(n,i) * an[n-i]
return an[n]
print("n\tan")
for m in range(10,101,10):
an = np.zeros(m+1)
print("%d\t%d"%(m,count_an(m,an)))