您的位置:首页 > 其它

程序碎片- 矩阵乘法优化(dp,递归)

2009-12-21 16:07 531 查看
using

System
;

using

System
.
Collections
.
Generic
;

namespace

SDProject

{

public

class
MartixMultiply

{

private

List
<
Martix
>
MList
;

public

MartixMultiply

()

{

initial

();

}

private

void
initial

()

{

Martix m1
=
new

MartixMultiply
.
Martix

(
2
,
5
);

Martix m2
=
new

MartixMultiply
.
Martix

(
5
,
100
);

Martix m3
=
new

MartixMultiply
.
Martix

(
100
,
4
);

Martix m4
=
new

MartixMultiply
.
Martix

(
4
,
50
);

Martix m5
=
new

MartixMultiply
.
Martix

(
50
,
6
);

Martix
[]
array
={
m1
,
m2
,
m3
,
m4
,
m5
};

this

.
MList
=
new

List
<
Martix
>(
array
);

}

int

[,]
M
=
new

int

[
5
,
5
];

public

void
GetBestSolutionByDP

()

{

//
设局部最优解是
M

i

j
】设矩阵
Ai
的维数是
P(i-1),

P(i)

//

M

i

j

=min{M

i

k

+M

k+1,j

+P(i-1)*P(k)*P(j)}

其中
i<=k<j

for

(
int

i
=
0
;
i
<
5
;
i
++)

for

(
int

j
=
0
;
j
<
5
;
j
++)

{

if

(
j
<=
i
)

{

M
[
i
,
j
]=
0
;

}

else


{

M
[
i
,
j
]=
Int32
.
MaxValue
;

}

}

int

finalResult
=
getOpt

(
0
,
4
);

Console
.
WriteLine

(
finalResult
);

}

private

int

getOpt

(
int

from
,
int

to
)

{

int

costform2K
;

int

costK2to
;

int

costMultiply2
;

int

costTotal
=
Int32
.
MaxValue
;

if

(
M
[
from
,
to
]!=
Int32
.
MaxValue
)

{

return
M
[
from
,
to
];

}

else


{

for

(
int

k
=
from
;
k
<
to
;
k
++)

{

costform2K
=
getOpt

(
from
,
k
);

costK2to
=
getOpt

(
k
+
1
,
to
);

costMultiply2
=
MList
[
from
].
orderX
*
MList
[
k
].
orderY
*
MList
[
to
].
orderY
;

int

tempcost
=
costform2K
+
costK2to
+
costMultiply2
;

if

(
costTotal
>
tempcost
)

{

costTotal
=
tempcost
;

M
[
from
,
to
]=
tempcost
;

}

}

return
costTotal
;

}

}

class
Martix

{

public

Martix

(
int

x
,
int

y
)

{

orderX
=
x
;

orderY
=
y
;

}

public

int

orderX
{
set
;
get
;}

public

int

orderY
{
set
;
get
;}

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: