poj 2229 Sumsets(dp 或 数学)

Description

Farmer John commanded his cows to search for different sets of numbers that sum to a given number. The cows use only numbers that are an integer power of 2. Here are the possible sets of numbers that sum to 7: 

1) 1+1+1+1+1+1+1 
2) 1+1+1+1+1+2 
3) 1+1+1+2+2 
4) 1+1+1+4 
5) 1+2+2+2 
6) 1+2+4 

Help FJ count all possible representations for a given integer N (1 <= N <= 1,000,000). 

Input

A single line with a single integer, N.

Output

The number of ways to represent N as the indicated sum. Due to the potential huge size of this number, print only last 9 digits (in base 10 representation).

Sample Input

7

Sample Output

6

Source

 

如果i为奇数,肯定有一个1,把f[i-1]的每一种情况加一个1就得到fi,所以f[i]=f[i-1]

如果i为偶数,如果有1,至少有两个,则f[i-2]的每一种情况加两个1,就得到i,如果没有1,则把分解式中的每一项除2,则得到f[i/2]

所以f[i]=f[i-2]+f[i/2]

由于只要输出最后9个数位,别忘记模1000000000

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<stdlib.h>
 6 #include<cmath>
 7 using namespace std;
 8 #define N 1010006
 9 #define MOD 1000000000
10 int n;
11 int dp[N];
12 void init(){
13     
14     dp[1]=1;
15     dp[2]=2;
16     for(int i=3;i<N;i++){
17         if(i&1){
18             dp[i]=dp[i-1];
19         }
20         else{
21             dp[i]=dp[i-1]+dp[i/2];
22             dp[i]%=MOD;
23         }
24     }
25 }
26 int main()
27 {
28     init();
29     while(scanf("%d",&n)==1){
30         
31         printf("%d
",dp[n]);
32     
33     }
34     return 0;
35 }
View Code
原文地址:https://www.cnblogs.com/UniqueColor/p/4783438.html