ABC 044 C - Tak and Cards
今天做了AtCoder Beginner Contest 044的C题:
Problem Statement
Tak has N cards. On the i-th (1≤i≤N) card is written an integer xi. He is selecting one or more cards from these N cards, so that the average of the integers written on the selected cards is exactly A. In how many ways can he make his selection?
Constraints
- 1≤N≤50
- 1≤A≤50
- 1≤xi ≤50
- N,A,xi
are integers.
大意就是从n个数中选i个数,并使它们的和为ni,求选的方法数。
显然,这是一道dp相关的题目(要求方案数),设dp[i][j][k]是在前i个数中选j(j>=1)个数、其和为k的方案总数。第i个数有选与不选2种可能,由此得出转移方程dp[i][j][k]=dp[i-1][j][k]+dp[i-1][j-1][k-x[i]](j>=1)
下面是代码
#include <iostream>
#include <cstdio>
#include <algorithm>
#define maxn 55
#define ll long long
using namespace std;
ll dp[maxn][maxn][maxn*maxn];
int x[maxn];
int n,A;
ll ans;
int main()
{
scanf("%d%d", &n, &A);
for (int i = 1; i <= n; i++)
{
scanf("%d", x + i);
}
for (int i = 0; i <= n; i++)
{
dp[i][0][0] = 1;
}
for (int i = 1; i <= n; i++)
{
for (int j = 0; j <= i; j++)
{
for (int k = 0; k <= n * A; k++)
{
if (k >= x[i] &&j>=1)
dp[i][j][k] = dp[i - 1][j][k] + dp[i - 1][j - 1][k - x[i]];//注意j此时要大于等于1,否则会访问错误的地方,我在这就卡了一阵子
else
dp[i][j][k] = dp[i - 1][j][k];
}
}
}
for (int t = 1; t <= n; t++)
ans += dp[n][t][t*A];
printf("%lld", ans);
return 0;
}
浙公网安备 33010602011771号