Weights and Measures——UVA10154

 更详细见http://www.cnblogs.com/staginner/archive/2011/11/30/2268497.html

题目

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 

题目大意

叠乌龟

每个乌龟有他所能承受的重量(包含他本身重量),将这个值成为力量

输入重量 和 力量

看能叠最多多少个乌龟

算法:贪心 

#include<iostream>
#include<algorithm>
#include<cstring>
#define INF 0x3f3f3f3f
using namespace std;
struct M{
	int w;
	int s;
}a[5700];
int f[5700];
int cmp(M a,M b)
{
	return a.s<b.s;
} 
int main()
{
	int n=0;
	while(cin>>a[n].w>>a[n].s) n++;
	sort(a,a+n,cmp);
	memset(f,INF,sizeof(f));
	int ans=0;
	f[0]=0;
	for(int i=0;i<n;i++)
		for(int j=ans;j>=0;j--)
		{												//更新最小重量和 
			if(a[i].s>=f[j]+a[i].w&&f[j]+a[i].w<f[j+1]) //如果最下边的承重能力大于前边的之前的所有重量和自己重量之和 
			{											//并且本身重量+前边的总重量小于j+1  
	         	f[j+1]=f[j]+a[i].w;                    		//更新 
	          	if(j+1>ans) ans=j+1;
	        }
		}
	cout<<ans<<endl;
	return 0;
}

 解析

 首先将乌龟按力量从小到大排序
这样我们是从上边开始叠,也就是每一次选一只乌龟放在最下边
定义一个f数组,用来存放叠了j个乌龟时,j的乌龟的最小重量和,f[0]=0,其他=inf 
ans用来统计乌龟数量 
从第一只乌龟开始筛选(然后内层循环来更新最小重量和
内层循环从ans开始 然后往最顶上的开始迭代
如果这只乌龟的力量比(叠了j个乌龟的j最小重量和)+(这只乌龟的重量)大
而且 (叠了j个乌龟的最小重量和)+(这只乌龟的重量)比 叠了j+1个乌龟的最小重量和)小 
那么就要更新j最小质量和了
然后判断如果j+1比ans大的话,更新ans (也就是放这只乌龟在最下边
如果不是j+1<ans 那么就把这只乌龟替换掉第j只乌龟

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cherish_lii

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值