错了2点,但不知道怎么改

P1478 陶陶摘苹果(升级版)

hexuchen @ 2023-06-30 10:35:26

测评结果

#include <bits/stdc++.h>
using namespace std;
struct apple{
    int gao,li;
};
bool cmp(apple a,apple b){
    return a.li<b.li;
}
int main(){
    int n,s2,sum=0,a,b;
    cin>>n>>s2>>a>>b;
    apple s[5001];
    for(int i=0;i<n;i++){
        cin>>s[i].gao>>s[i].li;
    }
    sort(s,s+n,cmp);
    for(int i=0;i<n;i++){
        if(s[i].gao<=(a+b)){
            s2-=s[i].li;
            if(s2<=0){
                cout<<sum;
                return 0;
            }
            sum++;
        }
    }
    return 0;
}

知道了错在

sum++;

但不知道怎么改QAQ


by miaowang555 @ 2023-06-30 10:41:52

你貌似没有在新一次循环将sum设为0.


by miaowang555 @ 2023-06-30 10:42:11

@miaowang555 貌似


by hexuchen @ 2023-06-30 10:48:17

@miaowang555 sum是有几个苹果啊,归零了苹果也归零了啊


by too_simple @ 2023-06-30 11:15:28

@hexuchen

#include <bits/stdc++.h>
using namespace std;
struct apple{
    int gao,li;
};
bool cmp(apple a,apple b){
    return a.li<b.li;
}
int main(){
    int n,s2,sum=0,a,b;
    cin>>n>>s2>>a>>b;
    apple s[5001];
    for(int i=0;i<n;i++){
        cin>>s[i].gao>>s[i].li;
    }
    sort(s,s+n,cmp);
    for(int i=0;i<n;i++){
        if(s[i].gao<=(a+b)){
            s2-=s[i].li;
            if(s2<0){
                break;
            }
            sum++;
        }
    }
    cout << sum << endl;
    return 0;
}

by too_simple @ 2023-06-30 11:16:04

改成小于0,然后n可能等于0


by hexuchen @ 2023-06-30 11:17:35

@too_simple 知道了,谢谢大神指导!


|