Week3: choose the number of questions --dfs traversal

A- number of election issues

Title Description
is given a positive integer n, to choose the number K, so as to satisfy these numbers is equal to S.
Calculated total number of possible options.

Input format
input containing a plurality of test samples.
The first line gives a positive integer T (<= 100) the number of test samples.

Next, for each test sample:
The first line contains three positive integer n, K, S;
second line contains n positive integer to be selected.

Output format
for each test case, output a integer answer.

Each test sample answers are each on a separate line.

Sample

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

4

Precautions

  • k<=n<=16
  • All integers are in the range of int32

Problem-solving ideas
This problem is typical of dfs traverse:
For each number, it has been selected and not selected either case, you only need recursively traverse all the points of all these two cases can be. However, this way will reach the time complexity O (2 ^ n), so we also need pruning operation.

For the current traversal state, in the following cases need pruning:

  • Selected is greater than the number of K
  • The selected number is greater than S

Sample Code

#include <iostream>
#include <vector>

using namespace std;

int t;
int n, k, s;
int a[16];
int ans;

//注意:这里的sum是倒着写的,即从目标S往下减
void fun(int nowsum,int i,vector<int> &counter)
{
    if (counter.size() == k && nowsum == 0)
    {
        ans++;//合法可能
        return;
    }
    if (counter.size() > k || nowsum < 0) return;//剪枝
  
    if (i >= n) return;

    fun(nowsum, i + 1, counter);//不选

    counter.push_back(a[i]);
    fun(nowsum - a[i], i + 1, counter);//选择
    counter.pop_back();
}


int main()
{
    cin >> t;
    while (t--)
    {
        ans = 0;
        cin >> n >> k >> s;
        int sum = s;
        vector<int>nowCount;
        for (int i = 0; i < n; i++)
        {
            cin >> a[i];
        }

        fun(s, 0, nowCount);
        cout << ans << endl;;
    }
}

Released five original articles · won praise 0 · Views 51

Guess you like

Origin blog.csdn.net/qq_44506233/article/details/104701899