Uva--10154(动规)
2014-08-04 23:50:01
Problem F: 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.
The Problem
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.
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.
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
思路:关键在看问题的角度,应该从stack的顶上往下考虑,这样递推比较自然,将龟龟的力量从小到大排个序。DP方程:dp[i][j]表示用前 i 个龟龟叠 j 层高的最低总重量。
DP方程:dp[i][j] = min(dp[i][j] , dp[i - 1][j] , dp[i - 1][j - 1] + w[i])
1 /************************************************************************* 2 > File Name: g.cpp 3 > Author: Nature 4 > Mail: 564374850@qq.com 5 > Created Time: Sun 03 Aug 2014 09:44:36 PM CST 6 ************************************************************************/ 7 8 #include <cstdio> 9 #include <cstring> 10 #include <cstdlib> 11 #include <cmath> 12 #include <iostream> 13 #include <algorithm> 14 using namespace std; 15 const int INF = 1e9; 16 17 struct node{ 18 int w,s; 19 }no[6000]; 20 21 int cnt = 1; 22 int dp[6000][6000]; 23 24 bool cmp(node a,node b){ 25 return a.s - a.w < b.s - b.w; 26 } 27 28 int main(){ 29 //freopen("in","r",stdin); 30 while(scanf("%d%d",&no[cnt].w,&no[cnt].s) == 2) 31 ++cnt; 32 sort(no + 1,no + cnt,cmp); 33 //printf("%d\n",cnt); 34 int ansmax = 0; 35 for(int i = 0; i < cnt; ++i) 36 for(int j = 1; j < cnt; ++j) 37 dp[i][j] = INF; 38 for(int i = 1; i < cnt; ++i){ 39 for(int j = 1; j <= i; ++j){ 40 dp[i][j] = dp[i - 1][j]; 41 if(no[i].s - no[i].w - dp[i - 1][j - 1] >= 0) 42 dp[i][j] = min(dp[i][j],dp[i - 1][j - 1] + no[i].w); 43 if(dp[i][j] < INF){ 44 //printf("dp[%d][%d] : %d\n",i,j,dp[i][j]); 45 ansmax = max(ansmax,j); 46 } 47 } 48 } 49 printf("%d\n",ansmax); 50 }