当前位置: 代码迷 >> 综合 >> poj - 1837 - Balance(dp)
  详细解决方案

poj - 1837 - Balance(dp)

热度:99   发布时间:2024-01-10 12:45:57.0

题意:一个天平,现要在其中的C(2 <= C <= 20)个位置(-15 <= x <= 15)挂G(2 <= G <= 20)个砝码(1 <= 单个质量 <= 25),问有多少种挂法使得天平平衡。

题目链接:http://poj.org/problem?id=1837

——>>状态:dp[i][j] 表示使用前 i 个砝码达到力矩和为 j 时的方案数。。

状态转移方程:dp[i][j] += dp[i - 1][j - w[i] * x[k]]。。

时间复杂度:O(C^2 * G^2)。。

#include <cstdio>
#include <cstring>const int OFFSET = 7500;
const int MAXN = 15000;
const int MAXC = 20 + 5;
const int MAXG = 20 + 5;int C, G;
int x[MAXC];
int w[MAXG];
int dp[MAXG][MAXN + 10];void Read()
{for (int i = 1; i <= C; ++i){scanf("%d", x + i);}for (int i = 1; i <= G; ++i){scanf("%d", w + i);}
}void Solve()
{memset(dp, 0, sizeof(dp));dp[0][OFFSET] = 1;for (int i = 1; i <= G; ++i){for (int k = 1; k <= C; ++k){int wx = w[i] * x[k];for (int j = 0; j <= MAXN; ++j){if (j - wx >= 0){dp[i][j] += dp[i - 1][j - wx];}}}}
}void Output()
{printf("%d\n", dp[G][OFFSET]);
}int main()
{while (scanf("%d%d", &C, &G) == 2){Read();Solve();Output();}return 0;
}