ACdream 1431——Sum vs Product——————【dfs+剪枝】

Sum vs Product

Time Limit: 2000/1000MS (Java/Others)    Memory Limit: 128000/64000KB (Java/Others)
Submit Status

Problem Description

      Peter has just learned mathematics. He learned how to add, and how to multiply. The fact that 2 + 2 = 2 × 2 has amazed him greatly. Now he wants find more such examples. Peters calls a collection of numbers beautiful if the product of the numbers in it is equal to their sum. 

      For example, the collections {2, 2}, {5}, {1, 2, 3} are beautiful, but {2, 3} is not. 

      Given n, Peter wants to find the number of beautiful collections with n numbers. Help him!

Input

      The first line of the input file contains n (2 ≤ n ≤ 500)

Output

      Output one number — the number of the beautiful collections with n numbers.

Sample Input

2
5

Sample Output

1
3

Hint

The collections in the last example are: {1, 1, 1, 2, 5}, {1, 1, 1, 3, 3} and {1, 1, 2, 2, 2}.
 
题目大意:让你求1---n中任意选n个数字,保证这n个数字加和与乘积相等,问有多少种方法。
 
 
解题思路:暴力搜索,加上剪枝。我们从2开始枚举,因为从2开始,乘积总是比加和的上升速度快。那么如果前m个数的和加上剩下的n-m个1的值还是小于前m个数的乘积的话,那么继续枚举就不可能有让最后的和跟积相等的情况了。所以这个剪枝会很剪掉很多情况。
 
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int n,sum;
void dfs(int cur,int sum1,int sum2,int dep){
    if(sum1+(n-dep)<sum2){
        return ;
    }
    if(sum1+(n-dep)==sum2){
        sum++;
        return ;
    }
    for(int i=cur;i<=n;i++){
        dfs(i,sum1+i,sum2*i,dep+1);
    }
}
int main(){
    while(scanf("%d",&n)!=EOF){
        sum=0;
        dfs(2,0,1,0);
        printf("%d
",sum);
    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/chengsheng/p/4859394.html