poj2229 dp

来源:互联网 发布:老外逛淘宝成瘾 编辑:程序博客网 时间:2024/06/10 14:03

 

 

如题:http://poj.org/problem?id=2229

Sumsets
Time Limit: 2000MS Memory Limit: 200000KTotal Submissions: 13748 Accepted: 5464

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

USACO 2005 January Silver

 

 

 

自己动手推一下,就会有答案。

 

dp[i]:i可以由2的幂的和组成的方法数。

 

如果i是奇数,dp[i]=dp[i-1]。因为如果是奇数,i可以由上一个偶数的所有方法数+1来完成,也可以由之前的某一个偶数+i-那个偶数完成,右侧+的那个一定是个奇数,这个奇数又可以继续拆成上一个偶数+1,所以通过1-N的递推,dp[i]=dp[i-1].

如果i是偶数,很容易想到,它首先可以由上一个偶数+1组成,或前某一个偶数+一个奇数完成,同上,其次,它还可以由全是偶数的组合组成。将每一种偶数拆分的每一个数都除以2,正好与dp[i/2]的一种拆分对应,dp[i]=dp[i-1]+d[i/2];

 

#include<iostream>
#include<cstdio>
using namespace std;

int dp[1000005];

int main()
{
 int N;
 scanf("%d",&N);
 int i;
 dp[1]=1;
 for(i=2;i<=N;i++)
 {
  if(i%2)
   dp[i]=dp[i-1];
  else
   dp[i]=dp[i-1]+dp[i/2];
  dp[i]%=1000000000;
 }
 cout<<dp[N]<<endl;
}

 

0 0
原创粉丝点击