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!
2 5
1 3
題解及代碼:
通過打表前幾項我們會發現構成n,比如n=5時,其形式之一是1 1 2 2 2,都是這種很多1,然後其他數字組合的形式。那麼我們就可以枚舉除了1以外的數字的組合,來計算sum[n]。比如數字組合為2 3 4,那麼根據公式我們知道2*3*4=24,2+3+4=9,那麼我們還需要補上15個1,加上2 3 4 這三個數字,總共是18個數字,那麼2 3 4必然屬於sum[18]裡面的一中情況。得到驗證,這樣我們就能用dfs來求出所有的情況數了。
下面的代碼是dfs的代碼,因為怕超時的緣故,題目AC的代碼是打表之後交的。
#include#include #include #include using namespace std; typedef long long ll; int sum[510]; void init() { memset(sum,0,sizeof(sum)); } void dfs(int nt,int nu,int su,int k) { for(int i=k;i<=500;i++) { if(nu*i>1000) break; sum[nu*i-su-i+nt+1]++; //printf("%d %d %d %d %d\n",nu,su,i,nt+1,nu*i-su-i+nt+1); dfs(nt+1,nu*i,su+i,i); } } int main() { init(); for(int i=2;i<=500;i++) dfs(1,i,i,i); for(int i=2;i<=500;i++) printf("%d,",sum[i]); return 0; }