Sumsets
Time Limit: 6000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2022 Accepted Submission(s): 797
Problem 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).
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
有两种方法,一种是递推,如果n为奇数,那么a[n]=a[n-1];
如果n为偶数的话,如果加数里面有1的话,肯定至少有两个,否则n就是奇数了,即a[n-2];
如果加数里面没有1的话,那么就是a[n/2]
#include<stdio.h>
int a[1000002],i,j,n;
int main()
{
int i;
a[1]=1;
a[2]=2;
a[3]=2;
a[4]=4;
for (i=5;i<=1000000;i++)
if (i%2==1)
a[i]=a[i-1]%1000000000;
else
a[i]=(a[i-2]+a[i/2])%1000000000;
while (~scanf("%d",&n))
printf("%d\n",a[n]);
return 0;
}
另一种是dp,还记得给你一个数字,求用比他小的数字之间的和来凑成这个数字的不同个数,原理是一样的,不过这里的加数变成了2的幂数了
即dp[j]+=dp[j-c[[i]],这里的数组c是关于2的幂次方
#include<stdio.h>
int dp[1000002],a[25],i,j,n;
int main()
{
a[0]=dp[0]=1;
for (i=1;i<=20;i++)
a[i]=a[i-1]<<1;
for (i=0;i<=20;i++)
for (j=a[i];j<=1000000;j++)
dp[j]=(dp[j]+dp[j-a[i]])%1000000000;
while (~scanf("%d",&n))
printf("%d\n",dp[n]);
return 0;
}