1. 程式人生 > >POJ 2229 遞推

POJ 2229 遞推

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

當 i 為奇數時可以將 i-1 的展開項加 1 得到 i 的展開項
當 i 為偶數是單純的將 i-1 的展開項加 1 無法得到所有的 i 的展開項,因為 i 是偶數,所以 i 的展開項中有全為偶數的情況
將全為偶數的展開像除以 2 得到的是 i/2 的展開項(可以倒著想,將 i/2 的展開項乘 2 得到 i 的全偶數展開項)

轉移式為 dp[i] = (i&1)?(dp[i-1]):(dp[i-1]+dp[i/2])

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4
using namespace std; 5 6 const int maxn = 1e6+5; 7 int dp[maxn]; 8 9 int main(){ 10 int n; 11 scanf("%d",&n); 12 memset(dp,0,sizeof(dp)); 13 dp[0] = 1; 14 15 for(int i=1;i<=n;++i){ 16 if(i&1) 17 dp[i] = dp[i-1]; 18 else{ 19 dp[i] = dp[i-1
] + dp[i>>1]; 20 if(dp[i]>1000000000) 21 dp[i] -= 1000000000; 22 } 23 } 24 25 printf("%d\n",dp[n]); 26 return 0; 27 }
View Code