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.
Partial Score
- 200 points will be awarded for passing the test set satisfying 1≤N≤16.
Input
The input is given from Standard Input in the following format:
N A x1 x2 … xN
Output
Print the number of ways to select cards such that the average of the written integers is exactly A.
Sample Input 1
4 8 7 9 8 9
Sample Output 1
5
- The following are the 5 ways to select cards such that the average is 8:
- Select the 3-rd card.
- Select the 1-st and 2-nd cards.
- Select the 1-st and 4-th cards.
- Select the 1-st, 2-nd and 3-rd cards.
- Select the 1-st, 3-rd and 4-th cards.
题目大意:
给你n个数字和一个数字a,求这n个数字的中任意取出x个数字,他们的平均数为a的情况的数量。
如给出4 8 7 8 9 9,那么平均数为8的情况有{8,7 9,7 9,7 8 9 ,7 8 9}(两个9不是同一个数字)五种情况
解析:
当时想了好多办法,对于2^50的可怕情况不能暴力,所以把所有的思路都集中在减少数据计算量上了,说到底还是一种暴力的思路,但是这个题目可以使用背包来解决,也就是使用f【j】【k】表示j个数字的和为k的情况的个数←看了题解
在使用背包解决的时候还遇到了几个小问题,第一,在循环遍历f[j][k]的时候,j采取递减的方式,否则会加重;第二,不仅仅是最后的和需要用longlong,在建立数组的时候也应该用longlong……
贴代码
#include<iostream>
#include<cstdio>
#include<map>
#include<sstream>
#include<cstring>
#include<algorithm>
#include<string>
using namespace std;
long long ans = 0;
int main()
{
int n,a,x;
cin >> n >> a;
long long f[60][2600];
memset(f,0,sizeof(f));
f[0][0] = 1;//零个数字的和为零的状况有一种
for(int i = 1; i <= n; i ++)
{
cin >> x ;
for(int j = i; j > 0; j --)//对于前i个数字
{
for(int k = x; k <= 2500; k ++)
{
f[j][k]+=f[j-1][k-x];
//if(f[j][k])cout <<"j: " << j << " k: " << k <<" fjk " << f[j][k] <<endl;
}
//cout << f[j][j*a] <<endl;
}
}
long long ans = 0;
for(int i = 1; i <= n; i ++)ans += f[i][a*i];
cout << ans <<endl;
return 0;
}