hdu 1028 Ignatius and the Princess III 完全背包
这题以前是母函数做的,今天看了DD的背包九讲,该用背包模型做。
这题是完全背包。设dp[i][v] 为用前i个数组成v的方案数,状态方程如下:dp[i][v] = sum(dp[i-1][v-k*i])
#include <iostream> using namespace std; const int N = 122; //dp[i][v] 为用前i个数组成v的方案数 //dp[i][v] = sum(dp[i-1][v-k*i]) int dp[N][N]; int main() { int n; while (cin >> n) { memset(dp, 0, sizeof(dp)); dp[0][0] = 1; for (int i = 1; i <= n; i++) for (int k = 0; k*i <= n; k++) for (int j = k*i; j <= n; j++) dp[i][j] += dp[i-1][j-k*i]; cout << dp[n][n] << endl; } return 0; }
可以优化成一维数组
for (int i = 1; i <= n; i++) for (int j = i; j <= n; j++) dp[j] += dp[j-i];