[Programming thinking and practice Week3 job] A number of election issues

Meaning of the questions:

Given n a positive integer, the K pick out, so that the K number was determined and S, how many programming access schemes.

Input:

The first line gives a positive integer T (T <= 100), T indicates a set of data. Next, each set of data over two lines, the first line gives the three numbers in question are intended to n, K, S; second row gives the n positive integers.

Sample Input:

1
10 3 10
1 2 3 4 5 6 7 8 9 10

Output:

For each set of data outputs an integer representing the number of programs, each output per line.

Sample Output:

4

Ideas:

The problem from the K n number of elected and to make and S, for each number are selected and not selected in both cases, so there are 2 ^ n kinds of situations, but the enumeration of high complexity, required for the case in which unreasonable eliminated directly, such as: and has greater than S, or the counted number is greater than k. In these cases, the selection process can be ruled out. Thus, using the recursive method, the number n sequentially selected and not selected for the determination, for a pathological case recursive process directly on a back, stop the recursion branch condition is satisfied in the case, the count variable +1, and returns to the previous, until you have selected all the data.

Errors:

After the end of a selected set of data, the number n is not the preservation containers emptying, such that a group of data before the next set of data results in impact errors.

Code:

#include <iostream>
#include<vector>
using namespace std;
int N,M,SUM;
vector<int> val;
int count=0;
void select(int i,int thesum,vector<int>&arr)
{
	if(arr.size()==M)
	{
		if(thesum==0)
			count++;
		return;
	}
	if(i>=N||thesum<0)
		return;
	select(i+1,thesum,arr);
	arr.push_back(val[i]);
	select(i+1,thesum-val[i],arr);
	arr.pop_back();
}

int main(int argc, char** argv) {
	int n;
	scanf("%d",&n);
	for(int i=0;i<n;i++)
	{
		val.clear();
		count=0;
		vector<int> arr;
		scanf("%d%d%d",&N,&M,&SUM);
		for(int j=0;j<N;j++)
		{
			int temp;
			scanf("%d",&temp);
			val.push_back(temp);
		}
		select(0,SUM,arr);
		if(i==0)
			printf("%d",count);
		else
			printf("\n%d",count);
	}
	return 0;
}
Published 25 original articles · won praise 8 · views 543

Guess you like

Origin blog.csdn.net/weixin_44034698/article/details/104716796