Weights and Measures (贪心+dp)

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
思路:先按照载重从小到大排序,然后dp即可,状态转移方程dp[t][j] = min(dp[t][j], dp[t-1][j-1] +p[t].a)。

代码:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#define INF 0x3f3f3f3f
using namespace std;

struct node {
	int a,b;

} p[10005];
long long int dp[10005][10005];
bool cmp(node x,node y)
{
	return x.b<y.b;
}
int main() {
	int n=1;
	while(scanf("%d%d",&p[n].a,&p[n].b)!=EOF) {
		n++;
	}
    n--;
    for(int t=0;t<=n;t++)
    {
    	for(int j=1;j<=n;j++)
    	{
    		dp[t][j]=INF;
		}
	}
	sort(p+1,p+n+1,cmp);
    for (int t = 1; t <= n; t ++)
	for (int j = 1; j <= t; j ++) {
	    dp[t][j] = dp[t-1][j];
	    if (dp[t-1][j - 1] + p[t].a <= p[t].b && dp[t-1][j-1] !=INF)
		dp[t][j] = min(dp[t][j], dp[t-1][j-1] +p[t].a);
	}
    int flag;
	for(int k=n;k>=1;k--)
	{
		if(dp[n][k]!=INF)
		{
			flag=k;
			break;
		}
	}
    printf("%d\n",flag);
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

black-hole6

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

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

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

打赏作者

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

抵扣说明:

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

余额充值