UVA11003 Boxes0-1背包

Posted 海岛Blog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UVA11003 Boxes0-1背包相关的知识,希望对你有一定的参考价值。

We have some boxes numbered 1 to N. The dimensions of all boxes are identical. Now we have to stack up some of the boxes, subject to the following constraints:

  1. One cannot put more than one boxes directly upon a box;
  2. Boxes with lower serial numbers are not to be put upon one with a higher number;
  3. The weight and maximum load for each box are given. The total weight of all boxes upon a box should not exceed its maximum load.

    Please write a program that finds the maximum number of boxes that can be stacked up according to the above constraints.
Input
The first line of each set of input is an integer N (1 ≤ N ≤ 1000). This is followed by N lines, each with two integers, both ≤ 3000, representing the weight and maximum load of each box respectively.
    Input ends with a case where N = 0.
Output
Each line of your output should give the number of boxes that can be stacked up.
Sample Input
5
19 15
7 13
5 7
6 8
1 2
0
Sample Output
4

问题链接UVA11003 Boxes
问题简述:(略)
问题分析:0-1背包问题,不解释。
程序说明:(略)
参考链接:(略)
题记:(略)

AC的C++语言程序如下:

/* UVA11003 Boxes */

#include <bits/stdc++.h>

using namespace std;

const int INF = 0x3F3F3F3F;
const int N = 1000;
struct Node {
    int w, s;
} a[N];
int dp[N + 1];

int main()
{
    int n;
    while (~scanf("%d", &n) && n) {
        for (int i = n - 1; i >= 0; i--) {
            scanf("%d%d", &a[i].w, &a[i].s);
            a[i].s += a[i].w;
        }

        for (int i = 0; i <= n; i++)
            dp[i] = INF;
        dp[0] = 0;
        for (int i = 0; i < n; i++)
            for (int j = n; j >= 1; j--)
                if (dp[j - 1] + a[i].w <= a[i].s)
                    dp[j] = min(dp[j], dp[j - 1] + a[i].w);

        int i;
        for (i = n; i >= 0; i--)
            if (dp[i] != INF) break;

        printf("%d\\n", i);
    }

    return 0;
}

以上是关于UVA11003 Boxes0-1背包的主要内容,如果未能解决你的问题,请参考以下文章

UVA 674 Coin Change (完全背包)

UVA - 12563 Jin Ge Jin Qu hao (01背包变形)

UVA624(01背包记录路径)

UVA 12563 "Jin Ge Jin Qu hao" (背包)

UVA 624CD(01背包输出 + 输出路径)

UVa 674 Coin Change(完全背包)