This is a question of greedy algorithm.First I have to say that if you want to execute this program immediately in Dev ,you will meet a serious mistake:
[Error] range-based ‘for’ loops are not allowed in C++98 mode
Therefore,you must finish some compiler configuration.I’ll attach the solution at the end of the article
Read this problem,and think of its meaning,you’ll find the answer.
#include<iostream>
#include<algorithm>
#include<list>
#include<stdlib.h>
using namespace std;
int elem[20];//定义一个数组存储输入的元素
int K,n,tag;
//sort(a,a+j,less<datetype>/greater<T>())
void select(int k,int sum,list<int> &res){//k
if(res.size() == K && sum==0){//递归终点
for(auto it:res) {
//cout<<it;
tag++;
}
//puts("");
return;
}
//边界
if(k>=n) return;
//判断合法
if(res.size() > K || sum < 0) return;
select(k+1,sum,res);//不选 ,相当于k++操作
res.push_back(elem[k]);//把第k个元素插到list尾部
select(k+1,sum-elem[k],res);//选
res.pop_back(); //删除最后一个元素
}
int main(){
int T,S;//Testdata,Sum
cin>>T;//select(0,sum,list)
for(int i=0;i<T;i++){
tag=0;
list<int> ways;
cin>>n>>K>>S;
for(int j=0;j<n;j++)
cin>>elem[j];
sort(elem,elem+n,less<int>());//升序排列
select(0,S,ways);
cout<<tag/K<<endl;
}
return 0;
}
Generally speaking, I used a recursive method to solve this problem.Let me explain my part of the code in detail <~~>
maybe the part of recursion:
if you don’t choose that figure,you need make the recursion positive,and then let ‘k’ do +1 again and again,at the same time,you insert the element into the list,if you choose,you let n reduce some numbers that have already been used and let list delete last element.The most important thing you need to recognize is that this question contains DFS.If you understand DFS,I insist that you could solve this problem easily.
OK,we need to solve the problem I have mentioned:
[Error] range-based ‘for’ loops are not allowed in C++98 mode
In order to work out this question,I refer to this blog.
Reference:https://blog.csdn.net/qq_39696269/article/details/81024071
Let me actually do it again:
first, open you Dev
second,clik tools
third ,click Compiler options:
fourth,modify the parameter
And everything will be OK,wish you good luck!