题意:
给一个数,是集合的总数和,集合元素只能为2的次幂数,问这样的集合有多少?
题目:
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+1+1+1+1+2
- 1+1+1+2+2
- 1+1+1+4
- 1+2+2+2
- 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
分析:
计数dp,dp[i]定义为i有多少种分解方案,
(1)对一个数
i
i
i,首先如果它是奇数,则它的方案总数与
i
−
1
i-1
i−1的方案总数相同,因为只需要在
i
−
1
i-1
i−1的每个分解方案集合里面多一个元素 1即可.
(2)如果它是偶数,则
i
/
2
i/2
i/2的每个分解方案的每个数*2即可得到
i
i
i,这样得到的
i
i
i的分解方案是不存在 1的(因为 *2所以至少为 2),因此还要考虑有 1的时候
i
i
i的分解方案有多少种,可以这样想,先忽略一个1,考虑剩下的数任意组合的方法数,也就是
i
−
1
i-1
i−1的方案数,最后再加上一个 1即可归为有 1的时候i的分解方案数,下面我会作图解答:
d
p
[
i
]
dp[i]
dp[i]=
i
i
i &1 ?
d
p
[
i
−
1
]
:
(
d
p
[
i
−
2
]
+
d
p
[
i
/
2
]
)
dp[i-1]:(dp[i-2]+dp[i/2])
dp[i−1]:(dp[i−2]+dp[i/2])%mod ;
初始化
d
p
[
0
]
=
d
p
[
1
]
=
1
dp[0]=dp[1]=1
dp[0]=dp[1]=1.递推就可以了.
AC模板:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int M=1e6+10;
const int mod=1e9;
typedef long long ll;
int n;
ll dp[M];
int main()
{
scanf("%d",&n);
dp[0]=dp[1]=1;
for(int i=2;i<=n;i++)
dp[i]=i&1?dp[i-1]:(dp[i-1]+dp[i/2])%mod;
printf("%lld\n",dp[n]);
return 0;
}