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[i][j]表示前i个乌龟叠j层时的重量。我们考虑dp[i][j]是如何转移过来的:
1.当dp[i-1][j]<dp[i][j]时,即前i-1个乌龟叠j层时的重量小于前i个乌龟叠j层时的重量,所以dp[i-1][j]要更优,
则此时dp[i][j]=dp[i-1][j];
2.当dp[i-1][j-1]+a[i].weight<dp[i-1][j]时,dp[i][j]=dp[i-1][j-1]+a[i].weight,因为相对于1时此时要更优。
综上可以得到状态转移方程:
dp[i][j]=min(dp[i-1][j],dp[i-1][j-1]+a[i].weight)
还有一个注意的地方,就是对乌龟的排序,我们按照力量从小到大排序
原因:https://www.cnblogs.com/staginner/archive/2011/11/30/2268497.html 转载大牛的文章,这个解释很清楚。
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
struct node{
int w;
int s;
}a[5700];
int dp[5700][5700];
bool cmp(node x,node y)
{
return x.s<y.s;
}
int main()
{
int x,y,n;
n=1;
memset(dp,0x3f3f3f3f,sizeof(dp));
while(~scanf("%d%d",&x,&y))
{
a[n].w=x;
a[n].s=y;
dp[n++][0]=0;
}
sort(a+1,a+1+n,cmp);
for(int i=1;i<=n;i++)
for(int j=1;j<=i;j++)
{
if(dp[i-1][j-1]!=0x3f3f3f3f&&dp[i-1][j-1]+a[i].w<dp[i-1][j]&&dp[i-1][j-1]+a[i].w<=a[i].s)
dp[i][j]=dp[i-1][j-1]+a[i].w;
else
dp[i][j]=dp[i-1][j];
}
for(int i=1;i<=n;i++)
if(dp[n][i]==0x3f3f3f3f)
{
printf("%d\n",i-1);
break;
}
return 0;
}