Program design thinking Week3- job number A- election issue

A- number of election issues

Description

Given n positive integers, the sum of them select the number K is S, n input requirements, K, S, output how many different choices.

Sample

input:
1
10 3 10
1 2 3 4 5 6 7 8 9 10
output:
4

Idea

First, I used the list to store the selected number, to facilitate adding elements, removing elements, you can also know the number of the selected time. Using selective recursive enumeration, for each number of terms, and are not selected select it considering its condition, each element added to a value corresponding to the sum is subtracted, and when the number of the list is equal to sum exactly equal to K 0, i.e., a qualified solution, while when K exceeds the number of list or not sum back in time in this case is recursively It has been less than zero.

Summary

The basic idea is enumerated, for the whole arrangement, each subset in turn determines whether to meet the requirements. In order to reduce complexity, must be selectively enumerate many cases obviously skip is not established, such as a subset of the number of elements exceeds K, and a subset of elements than S, occurs when the solution qualified back in time, because then further recursive added element must also not eligible.

Codes

#include <iostream>
#include <list>
using namespace std;
int a[16];
int t,n, k, s;
int amount = 0;
void solve(int i,int sum,list<int> &res) {
	if (res.size()==k&&sum == 0) { amount++; return; }
	if (i >= n)return;
	if (res.size()>k||sum < 0)return;

	solve(i + 1, sum,res);
	res.push_back(a[i]);
	solve(i + 1, sum - a[i],res);
	res.pop_back();

}

int main()
{
	cin >> t;
	while (t--)
	{
		amount = 0;
		scanf("%d%d%d", &n, &k, &s);
		memset(a, 0, sizeof(int));
		for (int i = 0; i < n; i++)
			cin >> a[i];
		list<int> r;
		solve(0, s, r);
		printf("%d\n", amount);

	}
}


Published 21 original articles · won praise 5 · Views 786

Guess you like

Origin blog.csdn.net/weixin_44578615/article/details/104711472