DP入门——01背包 & 完全背包
01背包:
采药:
https://www.luogu.org/problemnew/show/P1048
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <iostream> #include <algorithm> using namespace std; int dp[1005]; int weight[105],value[105]; int main() { int T, n; cin >> T >> n; for (int i = 0; i < n; i++) { cin >> weight[i] >> value[i]; } for (int i = weight[0]; i <= T; i++) { dp[i] = value[0]; } for (int i = 1; i < n; i++) { for (int j = T; j >= weight[i]; j--) { dp[j] = max(dp[j - weight[i]] + value[i], dp[j]); } } cout << dp[T] << endl; return 0; }
完全背包
疯狂采药:
https://www.luogu.org/problemnew/show/P1616
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <iostream> #include <algorithm> using namespace std; int dp[100005]; int weight[10005],value[10005]; int main() { int T, n; cin >> T >> n; for (int i = 0; i < n; i++) { cin >> weight[i] >> value[i]; } for (int i = weight[0]; i <= T; i++) { dp[i] = value[0] * (i / weight[0]); } for (int i = 1; i < n; i++) { for (int j = weight[i]; j <= T; j++) { dp[j] = max(dp[j - weight[i]] + value[i], dp[j]); } } cout << dp[T] << endl; return 0; }
区别在于,完全背包的初始化值,以及完全背包,每个东西可以用无限次,第二重循环是从前往后。