Sumsets
POJ - 2229
时限: 2000MS 内存: 200000KB 64位IO格式: %I64d & %I64u
已开启划词翻译
问题描述
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).
输入
A single line with a single integer, N.
输出
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).
样例输入
7
样例输出
6
题意:将一个数N分解为2的幂之和共有几种分法?
思路:亏我前面搞了好几道递归,结果到这题,知道是dp也在乱搞,思路一塌糊涂。
以后觉得像dp,就开始找他的子结构,找不到就先定义一个状态,比如这题dp[i]定义数字i的方案数,然后再分析,
假如i是奇数,那么i-1的式子中一定有个单独的1,把f[i-1]的每一种情况加一个1就得到f[i],所以f[i]=f[i-1]。
如果i为偶数,如果有1,那就至少两个,把i-2加两个1就好了,如果没有1将分解式每一项除以2,所以f[i]=f[i-1]+f[i/2];
由于只要输出最后9个数位,别忘记模1000000000
#include<cstdio>
#include<cstring>
int dp[1000100],n;
int main()
{
memset(dp,0,sizeof(dp));
dp[1]=1,dp[2]=2,dp[3]=2;
for(int i=4;i<=1000000;i++)
{
if(i%2) dp[i]=dp[i-1];
else dp[i]=dp[i-2]+dp[i/2];
dp[i]%=1000000000;
}
while(~scanf("%d",&n))
printf("%d\n",dp[n]);
}