为啥只有40分

P1478 陶陶摘苹果(升级版)

ThEskY_B1ackeR @ 2022-08-08 19:17:37

#include<bits/stdc++.h>
using namespace std;
struct t1{
    int x,y;//x=苹果高度,y=需要力气。 
}apples[5005];
int main(){
    int n,s,a,b;//n=数量,s=剩余力气,a=椅子高度,b=手伸直的最大长度。 
    cin>>n>>s>>a>>b;
    int num=0;
    for(int i=0;i<n;i++){
        int TU_height,TU_power;
        cin>>TU_height>>TU_power;
        if(TU_height<=a+b && TU_power<=s)apples[i].x=TU_height,apples[i].y=TU_power,num++;
    }
    int ans=0;
    for(int i=0;i<num-1;i++){
        for(int j=num-1;j>i;j--) if(apples[j].y<apples[j-1].y){
            int TU_number1=apples[j].x,TU_number2=apples[j].y;
            apples[j].x=apples[j-1].x,apples[j].y=apples[j-1].y;
            apples[j-1].x=TU_number1,apples[j-1].y=TU_number2;
        }
        s-=apples[i].y;
        if(s>=0) ans++;
        else break;
    }
    if(s-apples[num-1].y>=0)ans++;
    cout<<ans;
    return 0;
}

by ThEskY_B1ackeR @ 2022-08-08 19:18:33

qiuqiu帮助


by vanueber @ 2022-08-08 20:11:02

@ThEskY_B1ackeR

1.不应该s>=0就把答案+1,如果s=0就错了,可以特判一下

2.第十三行的赋值不能用i,把i改成num

我稍微修改了一下

#include <bits/stdc++.h>
using namespace std;
struct t1
{
    int x, y; // x=苹果高度,y=需要力气。
} apples[5005];
int main()
{
    int n, s, a, b; // n=数量,s=剩余力气,a=椅子高度,b=手伸直的最大长度。
    cin >> n >> s >> a >> b;
    if (s == 0)
    {
        cout << 0;
        return 0;
    }
    int num = 0;
    for (int i = 0; i < n; i++)
    {
        int TU_height, TU_power;
        cin >> TU_height >> TU_power;
        if (TU_height <= a + b && TU_power <= s)
            apples[num].x = TU_height, apples[num].y = TU_power, num++;
    }
    int ans = 0;
    for (int i = 0; i < num - 2; i++)
    {
        for (int j = num - 1; j > i; j--)
            if (apples[j].y < apples[j - 1].y)
            {
                int TU_number1 = apples[j].x, TU_number2 = apples[j].y;
                apples[j].x = apples[j - 1].x, apples[j].y = apples[j - 1].y;
                apples[j - 1].x = TU_number1, apples[j - 1].y = TU_number2;
            }
        s -= apples[i].y;
        if (s >= 0)
            ans++;
        else
            break;
    }
    if (s - apples[num - 1].y >= 0)
        ans++;
    cout << ans;
    return 0;
}

by ThEskY_B1ackeR @ 2022-08-08 20:14:04

@vanueber 谢谢帮助,我试试


by ThEskY_B1ackeR @ 2022-08-08 20:20:05

@vanueber 十分感谢,AC了


|