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).
题目大意: 给你一个数n,问你使用integer power of 2,(1, 2 ,4 8...) 这些数有多少种方法满足之和为n;
题目分析: d[i][v] 表示前i物品之和为v的最多数量, 有状态转移方程 d[i][v] = sum(d[i-1][v-k*c[i]] | 0 < k*c[i] <=v)
利用完全背包O(vn)优化的思想, 这里思想是相同的,则d[v] += d[v-c[i]]
参考代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = (int)1e6+10;
int n, d[maxn], c[30], m;
int Mod = (int)1e9;
void init(){
c[1] = 1;
for(int i = 2; ; ++i){
c[i] = c[i-1]*2;
if(c[i] >= maxn){
m = i; break;
}
}
}
int main()
{
init();
while(~scanf("%d", &n)){
memset(d, 0, sizeof(d));
d[0] = 1;
for(int i = 1; i < m; ++i){
if(c[i] > n) break;
for(int v = c[i]; v <= n; ++v){
d[v] += d[v-c[i]];
if(d[v] > Mod) d[v]%=Mod;
}
}
printf("%d\n", d[n]);
}
}