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). 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 Source |
分类,动态规划。
动态规划的特点就是对需要重复利用的结果进行记录,而不是重复计算。
这里是地推的思想,如果n是个奇数,那么满足要求的集合数其实是和n-1相同的,因为要求集合里的数都是2的幂(1,2,4,8...),所以sum为奇数的话,即合理必定有一个单独的无法合并的1;如果n是偶数,分为两种情况,如果集合里有1,那么一定是成对存在的,只需要n-2的集合里加入两个1即可,另一种情况是没有1,所有的数都是2的非0次幂,所有的数除以二,其实就是n / 2的所有集合,如此答案就是这两种的和。
代码:
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <algorithm> #define MAX 1000005 #define mod 1000000000 using namespace std; int s[MAX]; int main() { int n; scanf("%d",&n); s[0] = 1; for(int i = 1;i <= n;i ++) { if(i % 2)s[i] = s[i - 1]; else { s[i] = s[i - 1] + s[i / 2]; if(s[i] >= mod)s[i] -= mod; } } printf("%d",s[n]); }