poj2229

来源:互联网 发布:和布里兹学画画知乎 编辑:程序博客网 时间:2024/06/06 12:40

 

 

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

Sumsets
Time Limit: 2000MS Memory Limit: 200000KTotal Submissions: 14435 Accepted: 5755

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

 

 

 

 

思路:数据量100W,毫无疑问深搜栈会爆掉,因此假设dp[i]:i可以被2的次幂数组成的情况数,dp[n]就是结果。

然后从dp[1]开始写,dp[1]=1;dp[2]=dp[1];dp[3]=dp[2]+dp[1];

可以发现,对于任意的i和i-1,所有i-1的情况加进去一个1就是i的组合情况,然后对于奇数的i,这就是所有的情况了,对于偶数的i,还余一个2为基数的可以去组合,其余的情况就是没有1的,都能除尽2,这些情况中每个数/2就变成了dp[i/2]。

因此递推关系是就是

if(i%2)

dp[i]=dp[i-1];

else

dp[i]=dp[i-1]+dp[i/2];

最后别忘了取模

 

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define N 1000004
#define MOD 1000000000
int dp[N];

int main()
{
 int n;
 cin>>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]%=MOD;
 }
 cout<<dp[n]<<endl;
 return 0;
}

 

0 0
原创粉丝点击