hdu4314 Save the dwarfs(线性DP)

题目链接
Problem Description
Several dwarfs are trapped in a deep well. They are not tall enough to climb out of the well, so they want to make a human-pyramid, that is, one dwarf stands on another’s shoulder, until the dwarf on the top can reach the top of the well when he raise his arms up. More precisely speaking, we know the i-th dwarf’s height from feet to shoulder is Ai, and his arm length Bi. And we know the height of the well is H. If we can build a dwarf-tower consists of dwarf 1, dwarf 2, …, dwarf k from bottom to top, such that A1 + A2 + … + Ak-1 + Ak + Bk >= H, then dwarf k can escape from the well. Obviously, the escaped dwarf can’t be used to build tower again.

We want the escaped dwarfs as many as possible. Please write a program to help the dwarfs.

Input
The first line of each test case contains N, (1 <= N <= 2000) the number of trapped dwarfs. Each of the following N lines contains two integers Ai and Bi. The last line is H, the height of the well. All the integers are less than 100,000.

Output
Output one line for each test case, indicating the number of dwarfs escaped at most.

Sample Input
2
20 10
5 5
30
2
20 10
5 5
35

Sample Output
2
1
Hint
For the first case, the tall dwarf can help the other dwarf escape at first. For the second case, only the tall dwarf can escape.

Author
TJU

Source
2012 Multi-University Training Contest 2
思路:dp【i】表示前i个人跑出去后剩余身体和的最大值。

#include<bits/stdc++.h> 
#define ll long long
using namespace std;
const int maxn=2e3+5; 
pair<int,int>p[maxn];
bool cmp(const pair<int,int>&a,const pair<int,int>&b)
{
    return a.first+a.second<b.first+b.second;
}
int main()
{
    int n,h,dp[maxn];
    while(scanf("%d",&n)!=EOF)
    {
        dp[0]=0;
        for(int i=1;i<=n;++i) scanf("%d %d",&p[i].first,&p[i].second),dp[i]=-1,dp[0]+=p[i].first;
        sort(p+1,p+1+n,cmp);
        scanf("%d",&h);
        int k=0;
        for(int i=1;i<=n;++i)
        {
            for(int j=k;j>=0;--j)
            if(dp[j]+p[i].second>=h) dp[j+1]=max(dp[j+1],dp[j]-p[i].first);
            if(dp[k+1]!=-1) k++;
        }
        printf("%d\n",k);
    }
}
发布了328 篇原创文章 · 获赞 1 · 访问量 9105

猜你喜欢

转载自blog.csdn.net/qq_42479630/article/details/105209050