Sumsets
Time Limit: 2000MS | Memory Limit: 200000K | |
Total Submissions: 13788 | Accepted: 5480 |
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
本题两种思路 一种完全背包的思想 dp[i][j] 用2^i装满j的最大种数 然后写就可以了
另一种 我们可以观察递推式子
= = 然后我们发现 首先 偶数->奇数的时候 由于多了一个1 并且不会组成新的2 所以组合式子的个数并没有发生变化
但是 由奇数->偶数的时候 又多了一个组成了新的2 包含1的部分组合式子的个数与前一项奇数是一样的
不包含1的部分正如上图所示 为偶数除2那项的 组合个数 我们可以 正是那项每项都乘2
所以递推式子为 if(i&1) dp[i] = dp[i-1]; else dp[i] = dp[i-1] + dp[i>>1];
AC代码如下:
//
// POJ 2229 Sumsets
//
// Created by TaoSama on 2015-03-03
// Copyright (c) 2015 TaoSama. All rights reserved.
//
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <set>
#include <vector>
#define CLR(x,y) memset(x, y, sizeof(x))
using namespace std;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9;
const int N = 1e6 + 10;
int n, dp[N];
int main() {
#ifdef LOCAL
freopen("in.txt", "r", stdin);
// freopen("out.txt","w",stdout);
#endif
ios_base::sync_with_stdio(0);
dp[1] = 1;
for(int i = 2; i < N; ++i)
if(i & 1) dp[i] = dp[i - 1];
else dp[i] = (dp[i - 1] + dp[i >> 1]) % MOD;
while(cin >> n) {
cout << dp[n] << endl;
}
return 0;
}
//±³°üµÄ×ËÊÆ
/*
int n, c[25], dp[N];
int main() {
#ifdef LOCAL
freopen("in.txt", "r", stdin);
// freopen("out.txt","w",stdout);
#endif
ios_base::sync_with_stdio(0);
c[0] = dp[0] = 1;
for(int i = 1; i <= 20; ++i)
c[i] = c[i - 1] << 1;
for(int i = 0; i <= 20 && c[i] < N; ++i)
for(int j = c[i]; j < N; ++j)
dp[j] = (dp[j] + dp[j - c[i]]) % MOD;
while(cin >> n) {
cout << dp[n] << endl;
}
return 0;
}
*/