0-1背包问题 #include<iostream> #include<vector> #include<algorithm> #include<limits> using namespace std; int main() { int c, n; while(cin>>c>>n){ int p[101]; int v[101]; for (int i = 0; i < n; i++){ cin >> p[i] >> v[i]; } int dp[1001][102]; //dp[x][y] 在总额度不超过x块的情况下,考察0-y-1号商品的最大评分 for (int y = 0; y <= n; y++) { dp[0][y] = 0; } for (int x = 0; x <= n; x++) { dp[x][0] = 0; } for (int x = 1; x <= c; ++x) { for (int y = 1; y <= n; y++) { if (x - p[y - 1] < 0) { dp[x][y] = dp[x][y - 1]; } else dp[x][y] = max(dp[x][y - 1], dp[x - p[y - 1]][y-1] + v[y-1]); // 完全背包问题:dp[x][y] = max(dp[x][y - 1], dp[x - p[y - 1]][y] + v[y-1]); } } cout << dp[c][n] << endl; } return 0; }