Weights and Measures

I know, up on top you are seeing great sights, But down at the bottom, we, too, should have rights. We turtles can’t stand it. Our shells will all crack! Besides, we need food. We are starving!” groaned Mack. Mack, in an effort to avoid being cracked, has enlisted your advice as to the order in which turtles should be dispatched to form Yertle’s throne. Each of the five thousand, six hundred and seven turtles ordered by Yertle has a different weight and strength. Your task is to build the largest stack of turtles possible.

Input

Standard input consists of several lines, each containing a pair of integers separated by one or more space characters, specifying the weight and strength of a turtle. The weight of the turtle is in grams. The strength, also in grams, is the turtle’s overall carrying capacity, including its own weight. That is, a turtle weighing 300g with a strength of 1000g could carry 700g of turtles on its back. There are at most 5,607 turtles.

Output

Your output is a single integer indicating the maximum number of turtles that can be stacked without exceeding the strength of any one. Sample Input 300 1000 1000 1200 200 600 100 101 Sample Output 3

题目大意:
乌龟大国要灭亡了,现在需要你来拯救,通过搭建塔的方式,就是越高越好,因此在考虑的时候,先考虑乌龟的强度(strlength),然后考虑他的(weight),当然,如果(w>s)则直接放弃,好像也不太可能哈。

这是一个典型的0——1背包问题,由于自己是初学者,上网百度了下,特此总结如下。

0——1背包问题:

首先,将输入的数(有效的)输入到电脑里面。

我们确定按照哪一个元素进行排序,由小到大对s进行排序,如果s相同,按照w排序。

然后,就是核心环节了。

我们先取第一个元素s(最小的),找到一个d[p],时刻保存最小的w,想想为什么。如果满足那个等式的话,就ans进行选取。

求解完毕。

说得可能比较笼统,代码奉上。

代码:

#include <stdio.h>
#include <iostream>
#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;//先按照strength排序,然后按照重量排序 
}
 
int main() {
	while (scanf("%d%d", &w, &s) != EOF)//运用ctrl+z可以查看结果 
		if (s >= w)//不满足不存到数组 
			t[++n].wei = w, t[n].stg = s;//n为全局变量,初始值为0 
 
	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);//更新ans值 
				} 
		}
 
	printf("%d\n", ans);
 
	return 0;
}

注:代码初始选自如下,注释是自己的
*  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
*/
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值