Program work 3.a

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值