void MatrixChain(int *p,int n,int **m,int **s)
{
for(int i=1i<=ni++)
m[i][i]=0
for(int r=2r<=nr++)
for( i=1i<=n-r+1i++)
{
int j=i+r-1
m[i][j]=m[i+1][j]+p[i-1]*p[i]*p[j]
s[i][j]=i
for(int k=i+1k<jk++)
{
int t=m[i][k]+m[k+1][j]+p[i-1]*p[k]*p[j]
if(t<m[i][j])
{
m[i][j]=t
s[i][j]=k
}
}
}
}
void Traceback(int i,int j,int **s)
{
if(i==j)return
Traceback(i,s[i][j],s)
Traceback(s[i][j]+1,j,s)
cout<<"让 A"<<i//<<","<<s[i][j]
cout<<"和 A"<<(s[i][j]+1)<<"相乘"<<endl//<<举蚂尘","<<j<<"相乘"<<endl
}
void main()
{
int n,*p
int j=1
cout<<"请输入矩阵的个数"<<endl
cin>>n
p=new int[n+1]
cout<<"请输入第一个矩阵的行数,然后按正禅回车键"<<endl
cin>>p[0]
cout<<"第"<物燃<j<<"个矩阵是"<<endl
cout<<p[0]<<"*"
cin>>p[1]
// cout<<p[1]<<endl
cout<<endl
for(int i=2i<n+1i++)
{
cout<<"第"<<i<<"个矩阵是:"
cout<<p[i-1]<<"*"
cin>>p[i]
}
// int p[]={30,35,15,5,10,20,25}
// int m[6][6],s[6][6]
int **m,**s
m=new int*[n]
for( i=1i<=ni++)
m[i]=new int[n]
s=new int*[n]
for( i=1i<=ni++)
s[i]=new int[n]
MatrixChain(p,n,m,s)
Traceback(1,n,s)
}
这是矩阵连乘
#include <stdio.h>#include <limits.h>
#include<stdlib.h>
#define LENGTH 6
void MatrixChainOrder(int p[],int m[][LENGTH],int s[][LENGTH])
{
int n=LENGTH
int i,j,k,r,t
for(i=0i<ni++)
m[i][i]=0
for( r=1r<nr++)
{
for(i=0i<n-ri++)
{
j=i+r
m[i][j]=m[i][i]+m[i+1][j]+p[i]*p[i+1]*p[j+1]
s[i][j]=i
for(k=i+1k<jk++)
{
t=m[i][k]+m[k+1][j]+p[i]*p[k+1]*p[j+1]
printf("t=%d,m[%d][%d]=%d\锋袭尘n",t,i,j,m[i][j])
if(t<m[i][j])
{
m[i][j]=t
s[i][j]=k
}
}
}
}
}
int main()
{
int p[] = {30,35,15,5,10,20,25}
int m[LENGTH][LENGTH]
int s[LENGTH][LENGTH]
int i,j,k
MatrixChainOrder(p,m,s)
printf("最少数乘次数:\n")
for(i = 0i<LENGTHi++)
{ for(j = 0 j<=i j++ )
printf("")
for(k = ik<LENGTHk++)
printf("%8d",m[i][k])
printf("禅弯\n")
}
printf("断开位置:\n")
for(i = 0i<LENGTHi++)
{ for(j = 0 j<=i j++ )
printf("")
for(k = ik<LENGTHk++)
printf("%4d",s[i][k])
printf("\银禅n")
}
system("Pause")
return 0
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)