Sum vs Product(ACdream) —— dfs

I - Sum vs Product

Time Limit: 4000/2000MS (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}.
 
 
 
题意:给你一个数字n表示有n个数,让你找出这n个数的和与积相等的情况数。
 
分析:本来想找规律,但是有点不靠谱啊。刘大神说得好,等你找出规律来比赛都结束了,,所以果断搜索啊(不是我想到用搜索的 ==)。虽然数据比较大,但情况还是很少的,所以再剪剪枝就不会超时了。
 
p.s.我的搜索功底好差啊,,写了很久才写出来的。。
 
//num表示正要枚举的数,k表示有几个非1的数
//product表示积,sum表示和
#include<stdio.h>
int n, ans = 0;

void dfs(int num, int k, int product, int sum)
{
    for(int i=num; i>=2; i--)
    {
        if(product*i > sum+i+n-k) continue;
        else if(product*i == sum+i+n-k) ans++;
        else dfs(i, k+1, product*i, sum+i);
    }
}
int main()
{
    scanf("%d", &n);
    dfs(n, 1, 1, 0);
    printf("%d\n", ans);
    return 0;
}
//例:n=5:先是5 1 1 1 1,然后由于积小于和:5 5 1 1 1
//然后是5 4 1 1 1、5 3 1 1 1、5 2 1 1 1、4 4 1 1 1、、、

你可能感兴趣的:(DFS,ACdream)