Fat Brother Learns to Multiply DFS + 剪枝

Problem Description
When Fat Brother is a little child, he just shows his talent in mathematics. He was able to add and multiply at a very young age. Given a set of N integers, Fat Brother would feel happy if the sum of the integers in this set equals to the multiply of these integers. Now given an integer N, your task is to calculate how many sets with N integers would make little Fat Brother happy.
Input
The first line of the date is an integer T (1 <= T <= 20), which is the number of the text cases.

Then T cases follow, each case starts with a number N (2 <= N <= 500) indicated the number of the integers in the set.
Output
For each case, outputs the case number first, then output the number of the sets that would make little Fat Brother happy

See the sample input and output for more details.
Sample Input
2
2
5
Sample Output
Case 1: 1
Case 2: 3

解题思路:刚开始看到题目的时候都虚了,一直再想有没有什么特殊解法,结果只需要暴力DFS + 剪枝就可以。。。
只要积大于和的时候,无论如何枚举和都无法大于积了。
再者。枚举的时候从小到大枚举,因为集合是乱序的,所以这个也可以减去一大段的枝

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int ans;
void dfs(int num, int cur, int Sum, int ji, int Min) {
    if(cur == num && Sum == ji) { 
        ans++;
        return ;
    }
    if(cur > num || (cur == num && Sum != ji))
        return ;
    for(int i = Min; i <= num; i++) {
        Sum += i;
        ji *= i;
        if(ji > Sum)
            break;
        dfs(num,cur+1,Sum,ji,i);
        Sum -= i;
        ji /= i;
    }
}

int main() {
    int test, cas = 1, n;
    scanf("%d", &test);
    while(test--) {
        scanf("%d", &n);
        ans = 0;
        dfs(n,0,0,1,1);
        printf("Case %d: %d\n",cas++, ans);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值