20分求助!

P1478 陶陶摘苹果(升级版)

dingyyds11111 @ 2023-08-08 21:27:40

#include<bits/stdc++.h>
using namespace std;
struct node{
    int h;
    int l;
};
int main(){
    int n,s,a,b,ans=0,tl=0;
    cin>>n>>s;
    node t[5005];
    cin>>a>>b;
    a+=b;
    for (int i=0;i<n;i++){
        int h,l;
        cin>>h>>l;
        if(h>a) continue;
        t[tl].h=h;t[tl++].l=l;
    }

    for (int i=0;i<tl-1;i++){
        for (int j=i;j<tl-1;j++){
            if(t[j].l>t[j+1].l){
                swap(t[j],t[j+1]);
            }
        }
    }
    for (int i=0;i<tl;i++){
        if(s-t[i].l>=0){
            s-=t[i].l;
            ans++;
        }
        else {
            cout<<ans;
            return 0;
        }
    }
    return 0;
}

by GMH123456gmh @ 2023-08-08 22:16:47


#include<bits/stdc++.h>
using namespace std;
struct node{
    int h;
    int l;
}t[5005];
bool cmp(node x,node y){
    return x.l<y.l;
}
int main(){
    int n,s,a,b,ans=0,tl=0;
    cin>>n>>s;
    cin>>a>>b;
    a+=b;
    for (int i=0;i<n;i++){
        int h,l;
        cin>>h>>l;
        if(h>a) continue;
        t[tl].h=h;t[++tl].l=l;//其实这里不用’h'的;
    }
    sort(t+1,t+tl+1,cmp);
    for (int i=1;i<=tl;i++){
        if(s-t[i].l>=0){
            s-=t[i].l;
            ans++;
        }
        else {
            cout<<ans;
            return 0;
        }
    }
    cout<<ans;
    return 0;
}
如果题目后面要用到‘h'这串代码便不行了,我就不帮你改了;
你的错误是冒泡时应交换’l'和‘l'的值

|