博客园 首页 私信博主 显示目录 隐藏目录 管理 动画

bzoj:1677 [Usaco2005 Jan]Sumsets 求和

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).

给出一个N(1≤N≤10^6),使用一些2的若干次幂的数相加来求之.问有多少种方法

Input

   一个整数N.

Output

方法数.这个数可能很大,请输出其在十进制下的最后9位.

Sample Input

7

Sample Output

6

有以下六种方式
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
 
傻X一开始只想到了完全背包,以1,2,4……为容量即可
结果如下:
#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]);
}
然后看了一下黄学长的38MS代码
果然是hzw,方法如下:
如果i为奇数,显然f[i]=f[i-1],这个不难理解
如果i为偶数,就有f[i]=f[i-1]+f[i/2]
考虑所有构成f[i]的方案,对于其中含有1的方案,可以由f[i-1]来生成,不含1的方案中,每个数字都是2的倍数,那么只要把每个数字都除以2,就能与构成f[i/2]的方案一一对应,方案数也显然。
hzw果然是hzw……
附黄学长代码:
#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;
}
posted @ 2015-11-24 20:36  swm_sxt  阅读(207)  评论(0编辑  收藏  举报