Matrix Chain Multiplication-geeksforgeeks

(ABC)D = (AB)(CD) = A(BCD) calculate the least calculation.
        ,willl take np time.

def matrixp(p,i,j):
    if i==j:
        return 0
    k=i
    minval=10000000
    while k<j:
        result=matrixp(p,i,k)+matrixp(p,k+1,j)+p[i-1]*p[k]*p[j]
        if minval>result:
            minval=result
        k+=1
    return minval

def main():
    p=[40,20,10,30,10]
    print matrixp(p,1,len(p)-1)
    

if __name__=="__main__":
    main()

또 다른 방법은 동적 기획,bottom up solution
o(n^3) 공간이 필요합니다. o(n^2)
def matrixpp(p,n):
    minval=10000000
    m=[[0 for i in range(n)] for j in range(n)]
    for i in range(n):
        m[i][i]=0
        
    for L in range(2,n):
        for i in range(1,n-L+1):
            print j
            j=i+L-1
            m[i][j]=minval
            for k in range(i,j):
                q=m[i][k]+m[k+1][j]+p[i-1]*p[k]*p[j]
                if q<m[i][j]:
                    m[i][j]=q
    return m[1][n-1]
    
    

좋은 웹페이지 즐겨찾기