Python 图的最长路径的动态规划
我试图获得一个“快速”运行的算法,该算法给定一个可传递比赛的子图的邻接矩阵,计算最长路径的大小,目前我的代码如下所示:Python 图的最长路径的动态规划,python,graph,path,dynamic-programming,Python,Graph,Path,Dynamic Programming,我试图获得一个“快速”运行的算法,该算法给定一个可传递比赛的子图的邻接矩阵,计算最长路径的大小,目前我的代码如下所示: #this function defines the adjacency matrix of a transitive tournament on n vertices def transitive(n): A=np.zeros((n,n)) for i in range(n): for j in range(i+1,n):
#this function defines the adjacency matrix of a transitive tournament on n vertices
def transitive(n):
A=np.zeros((n,n))
for i in range(n):
for j in range(i+1,n):
A[i,j]=1
return(A)
#this one computes the adjacency matrix of a random subgraph of the graph defined above:
def Tp(A,p):
n=A.shape[0]
C=np.zeros(A.shape)
for i in range(n):
for j in range(n):
if A[i,j]!=0:
if random()>p:
C[i,j]=0
else:
C[i,j]=1
else:
C[i,j]=0
return(C)
我运行的算法是基本的动态规划,检查从每个顶点开始的最长路径
此函数用于检查从顶点i0开始的最长路径
def long_path(B,i0):
out_neighbours=np.where(B[i0,:]==1)[0]
if out_neighbours.size==0:
return 0
else:
return 1 + max([long_path(B,j) for j in list(out_neighbours)])
这一个迭代所有顶点并获得最长路径的大小
def longestpath(B,verbose=0):
n=B.shape[0]
lp=[0]*n
for i in range(n):
lp[i]=long_path(B,i)
if verbose==1:
print('For n=',n,' starting at index i0=',i,' we get a longest path of size :',lp[i])
return(max(lp))
这个算法实际上给了我一条最长路径的大小,但在遍历顶点时需要很多时间,我知道我可以通过以相反顺序运行最长路径(从最后一个顶点开始)并存储其大小,将计算时间传递到内存来节省大量时间,但我对python不够精通,不知道如何使用正确的语法来实现这一点
在这方面的任何帮助都将不胜感激 好吧,如果这对任何人都有用的话,我想做什么就做什么,把算法所做的大部分工作存储起来,现在它可以计算多达10000个顶点的图形,使用的时间与以前的500个顶点差不多
def longestpath_fast(B):
calculated_nodes=[0]*n
for step in range(n):
curr=n-step-1
K=B[curr:,:]
if curr==n-1:
calculated_nodes[curr]=0
else:
out_neighbours=np.where(B[curr,:]==1)[0]
if out_neighbours.size==0:
calculated_nodes[curr]=0
else:
calculated_nodes[curr]=1+max([calculated_nodes[s] for s in out_neighbours])
return(max(calculated_nodes),np.argmax(calculated_nodes))
它的计算与以前基本相同,但从最后一个顶点开始,并保存从该顶点开始的最大路径,该路径计算为从外邻居开始的最长路径的1+长度(该路径必须在列表的下方,因为此图是可传递的)。数据有多大,是否有闭合循环(我想不会,你的代码不会处理这种情况),你能发布一些示例数据吗?我的意思是,输入数据是由上面的函数给出的,我在500个顶点的图上运行它,p=log(n)/n,边太少。这个图是可传递的,所以它没有循环(它是一个有向图,所有边都指向更大的整数)。