信心满满切橙,20分AC第4点c++,蒟蒻求助qwq

P1478 陶陶摘苹果(升级版)

FengYuXinMing @ 2023-04-27 16:37:21

#include <bits/stdc++.h>
using namespace std;
int main(){
    int n,s,sum = 0,a,b;
    cin >> n >> s >> a >> b;
    int x[5005],y[5005]; 
    for (int i = 1;i <= n;i++){
        cin >> x[i] >> y[i];
    }
    for (int i = 1;i <= n;i++){
        if (x[i] <= b){
            if(s >= y[i]){
                s-=y[i];
                sum++;
            }
        }
        else{
            if (x[i] <= (a + b)){
                if (s >= y[i]){
                    s-=y[i];
                    sum++;
                }
            }
        }
    }
    cout << sum;
    return 0;
}

by jiangxinyang2012 @ 2023-04-27 16:48:15

@ababbjxzt 这题是贪心,要用结构体排序。

#include <bits/stdc++.h>
using namespace std;
struct g{
    int x,y;
};
bool cmp(g a,g b)
{
    if(a.y!=b.y)
        return a.y<b.y;
    return a.x<b.x;
}
int main(){
    int n,s,sum = 0,a,b;
    cin >> n >> s >> a >> b;
    g x[5005]; 
    for (int i = 1;i <= n;i++){
        cin >> x[i].x >> x[i].y;
    }
    sort(x+1,x+n+1,cmp);
    for (int i = 1;i <= n;i++){
        if (x[i].x <= b){
            if(s >= x[i].y){
                s-=x[i].y;
                sum++;
            }
        }
        else{
            if (x[i].x <= (a + b)){
                if (s >= x[i].y){
                    s-=x[i].y;
                    sum++;
                }
            }
        }
    }
    cout << sum;
    return 0;
}

提交记录


by onlyfiee @ 2023-04-27 17:08:20

@ababbjxzt 题目是指最多的苹果数目,肯定不是这样写的


by wing_yhc @ 2023-04-27 17:28:22

刷橙题之前还是要好好学

题目说了,用贪心+排序

那么看题,排序可以用冒泡或者sort函数,我们要在保证数量的同时,尽可能多得摘,所以先判断所需力气大小,再判断能否摘到。

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int n,s,a,b,x[5010],y[5010],high,ans,p;
int main(){
    cin>>n>>s;
    cin>>a>>b;
    high=a+b;
    for(int i=1;i<=n;i++){
        cin>>x[i]>>y[i];
    }
    for(int i=1;i<n;i++){
        for(int j=1;j<=n-i;j++){
            if(y[j]>y[j+1]){
                p=y[j+1];
                y[j+1]=y[j];
                y[j]=p;
                p=x[j+1];
                x[j+1]=x[j];
                x[j]=p;
            }
        }
    }
    for(int i=1;i<=n;i++){
      if(s>=y[i]&&high>=x[i]){
        ans++;
        s-=y[i];
      }
    }
    printf("%d",ans);
    return 0;
}

就是这样


by FengYuXinMing @ 2023-04-27 17:30:10

@2021Changqing60 是我轻敌了谢谢dalao


by FengYuXinMing @ 2023-04-27 17:32:08

@Wilsonyang8 橙题包括的知识点也挺多的哈谢谢dalao,我回炉重造了


by wing_yhc @ 2023-04-27 17:38:47

@ababbjxzt 加油


by GoodLuckCat @ 2023-06-18 10:09:15

601111?


|