背包问题

来源:互联网 发布:b站知名UP主黑历史知乎 编辑:程序博客网 时间:2024/06/06 02:24

神奇的口袋(百练2755)
总时间限制: 10000ms 内存限制: 65536kB
描述
有一个神奇的口袋,总的容积是40,用这个口袋可以变出一些物品,这些物品的总体积必须是40。John现在有n个想要得到的物品,每个物品的体积分别是a1,a2……an。John可以从这些物品中选择一些,如果选出的物体的总体积是40,那么利用这个神奇的口袋,John就可以得到这些物品。现在的问题是,John有多少种不同的选择物品的方式。
输入
输入的第一行是正整数n (1 <= n <= 20),表示不同的物品的数目。接下来的n行,每行有一个1到40之间的正整数,分别给出a1,a2……an的值。
输出
输出不同的选择物品的方式的数目。
样例输入
3
20
20
20
样例输出
3

#include <iostream>#include <cstdio>#include <cstring>#include <string>#include <algorithm>#include <map>#include <queue>#include <cmath>#include <vector>#include <functional>using namespace std;const int maxn = 45;int ways[maxn][maxn], a[maxn];int main(){    int n;    scanf ("%d", &n);    for (int i = 1; i <= n; i++) {        scanf ("%d", &a[i]);        ways[0][i] = 1;    }    ways[0][0] = 1;    for (int w = 1; w <= 40; w++) {        for (int i = 1; i <= n; i++) {            ways[w][i] = ways[w][i - 1];            if (w - a[i] >= 0) ways[w][i] += ways[w - a[i]][i - 1];        }    }    printf ("%d\n", ways[40][n]);    return 0;}

0-1背包(POJ3624)
Description
Bessie has gone to the mall’s jewelry store and spies a charm bracelet. Of course, she’d like to fill it with the best charms possible from the N (1 ≤ N ≤ 3,402) available charms. Each charm i in the supplied list has a weight Wi (1 ≤ Wi ≤ 400), a ‘desirability’ factor Di (1 ≤ Di ≤ 100), and can be used at most once. Bessie can only support a charm bracelet whose weight is no more than M (1 ≤ M ≤ 12,880).

Given that weight limit as a constraint and a list of the charms with their weights and desirability rating, deduce the maximum possible sum of ratings.

Input
* Line 1: Two space-separated integers: N and M
* Lines 2..N+1: Line i+1 describes charm i with two space-separated integers: Wi and Di

Output
* Line 1: A single integer that is the greatest sum of charm desirabilities that can be achieved given the weight constraints

Sample Input
4 6
1 4
2 6
3 12
2 7
Sample Output
23

#include <iostream>#include <cstdio>#include <cstring>#include <string>#include <algorithm>#include <map>#include <queue>#include <cmath>#include <vector>#include <functional>using namespace std;const int maxn = 3500;const int maxm = 12900;int w[maxn], d[maxn], sum[maxm];int main(){    int n, m;    while (scanf ("%d%d", &n, &m) != EOF ) {        memset (sum, 0, sizeof(sum));    memset (d, 0, sizeof(d));    memset (w, 0, sizeof(w));    for (int i = 1; i <= n; i++) {        scanf ("%d%d", &w[i], &d[i]);    }    for (int i = 1; i <= n; i++) {        for (int j = m; j >= w[i];j --) {            if (i == 1) {                sum[j] = d[i];                continue;            }            sum[j] = max (sum[j], sum[j - w[i]] + d[i]);        }    }    printf ("%d\n", *max_element (sum, sum + m + 1));    }    return 0;}
0 0
原创粉丝点击