-
Notifications
You must be signed in to change notification settings - Fork 430
/
备忘录递归实现.c
107 lines (74 loc) · 1.7 KB
/
备忘录递归实现.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include
using namespace std;
long MaxtrixChain1(int n);
long MaxtrixChain1(int i, int j);
int const MAX = 1000;
long subMatrixChain[MAX][MAX];
int bestK[MAX][MAX];
int dim[MAX];
int main()
{
int i, n;
while (cin >> n)
{
for (i = 0; i <= n; i++)
{
cin >> dim[i];
}
cout << MaxtrixChain1(n);
memset(subMatrixChain,-1,sizeof(subMatrixChain));
//cout << endl << subMatrixChain[5][1];
cout << "case 2:" << MaxtrixChain1(1,n);
}
return 0;
}
long MaxtrixChain1(int n)
{
int i,j,k,len;
for (i = 1; i <= n; i++)
{
subMatrixChain[i][i] = 0;
}
for (len = 2; len <= n; len++)
{
for (i = 1; i <= n - len + 1; i++)
{
j = i + len - 1;
subMatrixChain[i][j] = 100000000;
for (k = i; k < j; k++)
{
long ans = subMatrixChain[i][k] + subMatrixChain[k+1][j] + dim[i-1] * dim[k] * dim[j];
if (ans < subMatrixChain[i][j])
{
subMatrixChain[i][j] = ans;
bestK[i][j] = k;
}
}
}
}
return subMatrixChain[1][n];
}
long MaxtrixChain1(int i,int j)
{
if (subMatrixChain[i][j] != -1)
{
return subMatrixChain[i][j];
}
if (i == j)
{
subMatrixChain[i][j] = 0;
return 0;
}
long ans,max1 = 10000000;
for (int k = i; k < j; k++)
{
ans = MaxtrixChain1(i,k)+ MaxtrixChain1(k+1,j)+ dim[i-1] * dim[k] * dim[j];
if (ans < max1)
{
max1 = ans;
bestK[i][j] = k;
}
}
subMatrixChain[i][j] = max1;
return max1;
}