生活随笔
收集整理的這篇文章主要介紹了
算法设计与分析——动态规划——01背包问题
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
#include<iostream>
#include<iomanip>
using namespace std
;
int knapsack_problem( int n
,int *weight
,int *value
,int capacity
,int **m
,int *flag
)
{for(int i
=0;i
<=capacity
;i
++){m
[0][i
]=0;}for(int i
=0;i
<=n
;i
++){m
[i
][0]=0;} for(int i
=1;i
<=n
;i
++) {for(int j
=1;j
<=capacity
;j
++){if(j
<weight
[i
]) {m
[i
][j
]=m
[i
-1][j
]; }else{ m
[i
][j
]=max(m
[i
-1][j
],m
[i
-1][j
-weight
[i
]]+value
[i
]);}}} int temp_capacity
=capacity
;for(int i
=n
;i
>0;i
--){if(m
[i
][temp_capacity
]>m
[i
-1][temp_capacity
]){flag
[i
]=1; temp_capacity
=temp_capacity
-weight
[i
];}else{flag
[i
]=0;}}cout
<< "選中的物品是:";for(int i
=1;i
<=n
;i
++){cout
<<flag
[i
]<<" ";}cout
<<endl
;return m
[n
][capacity
];}
int main()
{int n
,capacity
;cout
<<"請(qǐng)輸入背包的最大容量:";cin
>>capacity
;cout
<<"請(qǐng)輸入物品的總數(shù):";cin
>>n
;int weight
[n
+1],value
[n
+1];cout
<<"請(qǐng)輸入物品的重量:";for(int i
=1;i
<=n
;i
++){cin
>>weight
[i
];}cout
<<"請(qǐng)輸入物品的價(jià)值:";for(int i
=1;i
<=n
;i
++){cin
>>value
[i
];}int **m
=new int *[n
+1];for(int i
=0;i
<=n
;i
++){m
[i
]=new int [capacity
+1];}int flag
[n
+1];cout
<< "獲得的最大價(jià)值為:"<<knapsack_problem(n
,weight
,value
,capacity
,m
,flag
)<<endl
;for(int i
=1;i
<=n
;i
++){for(int j
=1;j
<=capacity
;j
++){cout
<<setw(4)<<m
[i
][j
]<<" ";}cout
<<endl
;}}
總結(jié)
以上是生活随笔為你收集整理的算法设计与分析——动态规划——01背包问题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。