P1478 陶陶摘蘋果(升級版)

題目描述:已知n個蘋果到達地上的高度xi,椅子的高度a,陶陶手伸直的最大長度b,陶陶所剩的力氣s,陶陶摘一個蘋果需要的力氣yi,求陶陶最多能摘到多少個蘋果。
分析:貪心的基礎題,首先a + b是能摘到的蘋果的最大高度,所以最多能摘到的個數是一定的。按照根據所需力氣從小大大排序先摘所需力氣小的蘋果的策略就是最多的。
代碼:

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
using namespace std;
int n, s, a, b;
struct node       //結構體存每個蘋果高度和所需力氣
{
    int x, y;
}p[5005];
bool cmp(node c, node d)      //按照力氣從小到大排序
{
    return c.y < d.y;
}
int main()
{
    int i,j, t;
    while(~scanf("%d %d", &n, &s))
    {
        t = 0;
        scanf("%d %d", &a, &b);
        b = a + b;
        for (i = 0; i < n; i ++)
        {
            scanf("%d %d", &p[i].x, &p[i].y);
        }
        sort(p, p + n, cmp);
        for(i = 0; i < n; i++)
        {
            if(p[i].x <= b && s >= p[i].y)
                {
                    t ++;
                    s -=p[i].y;
                }
        }
        printf("%d\n", t);
    }
    return 0;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容