week3作业 A - 选数问题

Given nn positive numbers, ZJM can select exactly KK of them that sums to SS. Now ZJM wonders how many ways to get it!InputThe first line, an integer T<=100T<=100, indicates the number of test cases. For each case, there are two lines. The first line, three integers indicate nn, KK and SS. The second line, nn integers indicate the positive numbers.OutputFor 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<=16k<=n<=16 and all numbers can be stored in 32-bit integer
Sponsor
解题思路:
这是选数问题,采用DFS的思想,对这n个数进行遍历。不过其中有很多情况其实是不需要遍历的,所以我们可以进行剪枝。这里采用的是重复性剪枝。从第一个数开始选,选取数的位置是递增的。用一个参数来记录上一次选取的数的位置,此次选择从这个数之后开始选取。

#include <iostream>
#include<cstring>
using namespace std;
int n, k, sum, ans;
int a[40];
bool xuan[40];
void dfs(int s, int cnt,int pos) {
    if(s>sum||cnt>k){
  return ;
    }
    if (s == sum && cnt == k) {
        ans++;
    }
    for (int i = pos; i < n; i++) {
        if (!xuan[i]) {
            xuan[i] = true;
            dfs(s + a[i], cnt + 1,i+1);
            xuan[i] = false;
        }
    }
}
int main() {
 int t;
 scanf("%d",&t);
 for(int i=0;i<t;i++)
 {
     scanf("%d%d%d",&n,&k,&sum);
     memset(a,0,sizeof(a));
     memset(xuan,false,sizeof(xuan));
    for (int j= 0; j<n; j++) {
           scanf("%d",&a[j]); 
      }
    ans = 0;
    
    dfs(0, 0,0);
    cout << ans << endl;
    }
    return 0;
}
//重复性剪枝:
//选出来的数的位置是递增的,用一个参数来记录上一次选取的数的位置,此次选择从这个数之后开始选取,最后选出来的方案不会重复
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值