junior19

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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.

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
题意:有很多只王八,各有一个重量值和力量值,问最多能叠起来多少只王八,其中每只王八的重量值也要靠自身的力量值支撑。

思路:首先将他们按力量值有小到大排序,因为假如两只王八i,j,其中p[i] > p[j],如果将i叠在j上面是可行的(说明w[i] + w[j] 是小于等于 p[j]的),那么将j叠在i上面也一定可行,且获得更优的解,因为p[i] - (w[i] + w[j])大于p[j] - (w[i] + w[j]),原来p[i] - (w[i] + w[j]) 也变成p[i] - w[i],整体的可承受重量都增加了,最后dp一下即可。

# include <iostream>
# include <cstdio>
# include <cstring>
# include <algorithm>
# define MAXN 5610
# define INF 0x3f3f3f3f
using namespace std;
int w[MAXN], p[MAXN], id[MAXN], dp[MAXN];


bool cmp(int a, int b)
{
    return p[a] < p[b];
}


int main()
{
    int n=1, ans;
    while(~scanf("%d%d",&w[n],&p[n])) {id[n]=n; ++n; }
    sort(id+1, id+n, cmp);
    memset(dp, INF, sizeof(dp));
    dp[0] = 0;
    for(int i=1; i<=n; ++i)
        for(int j=n-1; j>=1; --j)
            if(p[id[i]]-w[id[i]] >= dp[j-1] && dp[j-1] != INF)
                dp[j] = min(dp[j], dp[j-1]+w[id[i]]);
    for(int i=n-1; i>=1; --i)
        if(dp[i] != INF)
        {
            ans = i;
            break;
        }
    printf("%d\n",ans);
    return 0;
}

 


posted on 2017-03-04 13:24  junior19  阅读(150)  评论(0编辑  收藏  举报