1. 程式人生 > >【Weights and Measures】【UVA - 10154】(dp)

【Weights and Measures】【UVA - 10154】(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[j]  的值(代表第j個烏龜的總重量)。

ac程式碼:

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<cmath>
using namespace std;
typedef long long ll;

const int maxn =1e5+1000;

struct node{
	int power;
	int weight;
}num[maxn];
int dp[maxn];
bool cmp(node a,node b)
{
	if(a.power==b.power)
		return a.weight<b.weight;
	return a.power<b.power;
}
int main()
{
	int n=1;
	while(scanf("%d%d",&num[n].weight,&num[n].power)!=EOF)
		n++;
	sort(num+1,num+n,cmp);
	n--;
	for(int i=1;i<=n;i++)
		dp[i]=999999999;
	dp[0]=0;
	int ans=1;
	for(int i=1;i<=n;i++)
		for(int j=n;j>=1;j--)
		{
			if(dp[j-1]+num[i].weight<=num[i].power)
				dp[j]=min(dp[j],dp[j-1]+num[i].weight);//更新第j個烏龜放上之後的總重量
			if(dp[j]<999999999)
				ans=max(j,ans);
		}
	printf("%d\n",ans);
} 
/*
300 1000
1000 1200
200 600
100 101
*/