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).
给出一个N(1≤N≤10^6),使用一些2的若干次幂的数相加来求之.问有多少种方法
方法数.这个数可能很大,请输出其在十进制下的最后9位.
#include<cstdio>
using namespace std;
const int MOD=1e9;
int n,dp[1000001];
int main(){
scanf("%d",&n);
dp[0]=1;
for (int i=1;i<=n;i*=2){
for (int j=i;j<=n;j++) dp[j]=dp[j]+dp[j-i],dp[j]-=dp[j]>=MOD?MOD:0;
}
printf("%d\n",dp[n]);
}
考虑所有构成f[i]的方案,对于其中含有1的方案,可以由f[i-1]来生成,不含1的方案中,每个数字都是2的倍数,那么只要把每个数字都除以2,就能与构成f[i/2]的方案一一对应,方案数也显然。
#include<cstdio>
#include<iostream>
using namespace std;
const int maxn=1002333;
const int modd=1000000000;
int f[1000001],i,n;
int main(){
scanf("%d",&n);f[1]=1;
for(i=2;i<=n;i++)if(i&1)f[i]=f[i-1];else {f[i]=f[i-1]+f[i>>1];if(f[i]>=modd)f[i]-=modd;}
printf("%d\n",f[n]);
return 0;
}