A - 选数问题(Week3作业)

题目描述

Given n positive numbers, ZJM can select exactly K of them that sums to S. Now ZJM wonders how many ways to get it!

Input

The first line, an integer T<=100, indicates the number of test
cases. For each case, there are two lines. The first line, three
integers indicate n, K and S. The second line, n integers indicate the
positive numbers.

Output

For each case, an integer indicate the answer in a independent line.

Example

Input

1

10 3 10

1 2 3 4 5 6 7 8 9 10

Output

4

Note

Remember that k<=n<=16 and all numbers can be stored in 32-bit integer

题目思路:

对于这道题可以利用递归实现,为避免无效操作,我们每次从上一个加入count的数字后面开始遍历选择,即在递归时多传入一个参数记录当前数字对应的索引,下一次递归时从这个数字的下一位开始遍历递归。
当遍历到n层时,如果此时count刚好等于我们想要的那个值,ans++,否则,返回上一层。

代码实现:

#include<bits/stdc++.h>
using namespace std;
int n,k,s,ans;
int a[16];
bool flag=false;
void fun(int count,int kk,int d)//d代表上一层数对应的索引
{
 if(kk==0)
 {
  if(count==s)
  {
   ans++;
   return; 
  }
 }
 else{
  for(int i=d;i<n;i++)
  {
   fun(count+a[i],kk-1,i+1);
  }
 }
}
int main()
{
 
 int N;
 scanf("%d",&N);
 while(N--)
 {
  ans=0;
  scanf("%d %d %d",&n,&k,&s);
  for(int i=0;i<n;i++)
  {
   scanf("%d",&a[i]); 
  }
  fun(0,k,0);
  printf("%d\n",ans);
 }
}
发布了24 篇原创文章 · 获赞 9 · 访问量 7175

猜你喜欢

转载自blog.csdn.net/qq_40103496/article/details/104828917