UVA 10154 Weights and Measures 01背包

来源:互联网 发布:寸心草软件 编辑:程序博客网 时间:2024/05/17 09:28

题意:给出n只乌龟的体重和能承受的重量,它自己的体重也要承受,要把乌龟们叠起来,问最多能叠到多高。

其实就是变形的01背包,先把乌龟按力量排序,然后再进行01背包。

代码:

/**  Author:      illuz <iilluzen[at]gmail.com>*  Blog:        http://blog.csdn.net/hcbbt*  File:        uva10154.cpp*  Create Date: 2013-11-09 11:13:55*  Descripton:  dp*/#include <cstdio>#include <algorithm>using namespace std;const int MAXN = 6000;const int MAX = 0x7ffffff;struct Turtle {int wei, stg;} t[MAXN];int w, s, n, dp[MAXN];bool cmp(const Turtle &a, const Turtle &b) {if (a.stg != b.stg)return a.stg < b.stg;return a.wei < b.wei;}int main() {while (scanf("%d%d", &w, &s) != EOF)if (s >= w)t[++n].wei = w, t[n].stg = s;sort(t + 1, t + n + 1, cmp);for (int i = 1; i <= n; i++)dp[i] = MAX;int ans = (n ? 1 : 0);for (int i = 1; i <= n; i++)for (int j = n; j >= 1; j--) {if (t[i].stg >= dp[j - 1] + t[i].wei)dp[j] = min(dp[j], dp[j - 1] + t[i].wei);if (dp[j] < MAX)ans = max(ans, j);}printf("%d\n", ans);return 0;}


原创粉丝点击