试题:
思路:
经典的0-1背包问题,这题坑的地方在于方案数会超过边界,当发现当前重量可行时,直接归为1,防止dp数组累加时溢出。或者最后统计的时候,将判断条件从if(dp[n][i])>0
改为if(dp[n][i])
。
动态转移方程:
dp[i][j] = dp[i-1][j] + dp[i-1][j+weight[i]] + dp[i-1][abs(j-weight[i])]
边界条件:
dp[0][0] = 1
参考代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int dp[105][200005];int main()
{ios::sync_with_stdio(false);int weight[105], n, m = 0;cin >> n;for(int i = 1; i <= n; i++){cin >> weight[i];m += weight[i];}dp[0][0] = 1;for(int i = 1; i <= n; i++){for(int j = 0; j <= m; j++){dp[i][j] = dp[i-1][j] + dp[i-1][j+weight[i]] + dp[i-1][abs(j-weight[i])];if(dp[i][j] > 0)dp[i][j] = 1;}}int count = 0;for(int i = 1; i <= m; i++){if(dp[n][i] > 0)count++;}cout << count << endl;return 0;
}