Program work 3.a
A - 选数问题
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
思路
以递归的思路,select(i+1,sum,res); 是不选第一个,然后对后面的进行select,出来之后,res.push_back(a[i]); select(i+1,sum-a[i],res);两行是选第一个,然后对后面的进行select(此时S变为S减去第一个元素),出来之后,res.pop_back(); 将这一层select所push进去的那个元素pop掉,使执行完该层select后的res链表恢复原状。
在上面的整个过程中间,一旦满足res.size()==K && sum ==0的条件,num就自增1,同时如果需要输出方案,也可以将整个数组输出出去(注释部分)
Answer
具体思路见注释
#include <iostream>
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
#include<list>
using namespace std;
const int maxn = 100;
int K,S,num=0,n,a[maxn];
void select(int i,int sum,list<int>&res){
if(res.size()==K && sum ==0){//符合条件
num++;
//若需要输出方案
//for(auto x:res)printf("%d",x);
return;
}
//判断边界
if(i>=n)return;
//可行性剪枝
if(res.size()>K || sum < 0) return;
select(i+1,sum,res);//不选
res.push_back(a[i]);
select(i+1,sum-a[i],res);//选
res.pop_back();
}
int main(){
int T;
cin>>T;
while(T--){
cin>>n>>K>>S;
for(int i=0;i<n;i++)cin>>a[i];
list<int> res;
select(0,S,res);
cout<<num<<endl;
num=0;
}
return 0;
}