1. 程式人生 > >P1478 陶陶摘蘋果(升級版)洛谷 (c++)(貪心、排序)

P1478 陶陶摘蘋果(升級版)洛谷 (c++)(貪心、排序)

由題意分析可知,每次摘得蘋果的條件是椅子的高度加手伸直的最大長度大於等於蘋果的高度並且剩餘力氣值必須大於等於所摘蘋果需要的力氣值,每摘一個蘋果力氣值相應減少,問題則是在此條件下求解能摘到的最多蘋果數。我們可以以貪心的思想考慮,每次在符合高度的條件下摘取所需要最小力氣的蘋果,由此可以得出答案。而如何選取每次需要最小力氣的蘋果呢?那就可以通過結構體排序來解決,將摘蘋果所需要的力氣按升序排列或者降序排列,符合條件計數器加1,力氣相應減少。程式碼如下:

#include<stdio.h>
#include<cstring>
#include<algorithm>
#include<vector>
#include<map>
#include<set>
#include<cmath>
#include<iostream>
#include<string>

using namespace std ;

typedef struct{
    int x ;
    int y ;
}mea ;

bool cmp( mea a , mea b ){
    return a.y < b.y ;                //使其升序排列
}

int main(){
    mea arr[5005] ;
    int n , s ;
    cin >> n >> s ;
    int a , b ;
    cin >> a >> b ;
    int tot = a + b ;
    for ( int i = 0 ; i < n ; i ++ ){
        cin >> arr[i].x >> arr[i].y ;
    }
    sort( arr , arr + n , cmp ) ;
    int num = 0 ;
    for ( int i = 0 ; s >= 0 && i < n ; i ++ ){
//        cout << arr[i].x << " " << arr[i].y << endl ;
        if ( tot >= arr[i].x && s >= arr[i].y ){
            s -= arr[i].y ;
            num ++ ;
        }
    }
    cout << num ;
    return 0 ;
}