牛牛的背包问题
牛牛準備參加學校組織的春游, 出發前牛牛準備往背包里裝入一些零食, 牛牛的背包容量為w。
牛牛家里一共有n袋零食, 第i袋零食體積為v[i]。
牛牛想知道在總體積不超過背包容量的情況下,他一共有多少種零食放法(總體積為0也算一種放法)。
輸入描述:
輸入包括兩行
第一行為兩個正整數n和w(1 <= n <= 30, 1 <= w <= 2 * 10^9),表示零食的數量和背包的容量。
第二行n個正整數v[i](0 <= v[i] <= 10^9),表示每袋零食的體積。
輸出描述:
輸出一個正整數, 表示牛牛一共有多少種零食放法。
輸入例子1:
3 10
1 2 4
輸出例子1:
8
例子說明1:
三種零食總體積小于10,于是每種零食有放入和不放入兩種情況,一共有2*2*2 = 8種情況。
遞歸超時
動態規劃 ,注意要用 long, 因為牛牛的背包巨大
#include <iostream> #include <map> #include <vector>using namespace std;struct cmp_key {bool operator()(const long &a, const long &b) const{return a > b;} };int main() {long vBag = 0;int nSnack = 0;cin >> nSnack >> vBag;vector<long> v(nSnack, 0);// v, nummap<long, int, cmp_key> mp;mp[0] = 1;for (int i = 0; i != nSnack; ++i) {cin >> v[i];}for (int i = 0; i != nSnack; ++i) {for (auto it = mp.begin(); it != mp.end(); ++it) {long key = it->first;int val = it->second;long newKey = key + v[i];if (newKey > vBag) continue;mp[newKey] += mp[key];}}int cnt = 0;for (auto it = begin(mp); it != end(mp); ++it) {cnt += it->second;}cout << cnt << endl; }總結
- 上一篇: PropertyUtils与BeanUt
- 下一篇: 从RTS游戏看游戏开发-2