-
Notifications
You must be signed in to change notification settings - Fork 49
/
fractional knapsack.cpp
105 lines (51 loc) · 1.3 KB
/
fractional knapsack.cpp
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
# include<bits/stdc++.h>
using namespace std;
void print( vector<vector<int>>&s,int i,int j){
if(i==j){
cout<<"A";
}
else{
cout<<"(";
print(s,i,s[i][j]);
print(s,s[i][j]+1,j);
cout<<")";
}
}
//0(n^3)
void mcm(vector<int>arr){
int n = arr.size();
vector<vector<int>>dp(n-1,vector<int>(n-1,0));
vector<vector<int>>s(n-1,vector<int>(n-1,0));
for(int g=0; g<n-1; g++){
for(int i=0, j=g; j<n-1; i++,j++){
if(g==0){
dp[i][j]=0;
}
else if(g==1){
dp[i][j]=arr[i]*arr[j]*arr[j+1];
s[i][j]=i;
}
else{
dp[i][j]=INT_MAX;
for(int k=i; k<j ; k++){
int tc= dp[i][k]+dp[k+1][j]+(arr[i]*arr[k+1]*arr[j+1]);
if(tc<dp[i][j]){
dp[i][j]= tc;
s[i][j]=k;
}
}
}
}
}
cout<<dp[0][n-2];
print(s,0,n-2);
}
int main(){
int n;
cin>>n;
vector<int>v(n,0);
for(int i=0; i<n; i++){
cin>>v[i];
}
mcm(v);
}