[洛谷P1478] 陶陶摘苹果升级版 (Java)

本文介绍使用Java解决经典算法问题“陶陶摘苹果”的方法。通过LinkedList和Apple类,实现了苹果的存储和排序,确保苹果在可及范围内且力量足够时进行采摘。文章详细展示了如何读取输入,筛选符合条件的苹果,并最终输出可采摘的苹果数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

传送门:P1478 陶陶摘苹果(升级版)

俺又来水 Java 了。熟悉的陶陶摘苹果,用 C++ 秒写完的东西,用 Java 写了半天...

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;

public class P1478 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int s = scanner.nextInt();
        int a = scanner.nextInt();
        int b = scanner.nextInt();
        int c = a + b;
        int ans = 0;
        LinkedList<Apple> applesList = new LinkedList<Apple>();
        for (int i = 0; i < n; ++i) {
            int x = scanner.nextInt();
            int y = scanner.nextInt();
            if (x <= c) {
                applesList.add(new Apple(x, y));
            }
        }

        Apple[] apples = new Apple[applesList.size()];
        apples = applesList.toArray(apples); // 利用反射将Object[] 转换成 Apple[]
        Arrays.sort(apples);
        for (Apple apple: apples) {
            if (apple.isReachable(c)) {
                if ((s = apple.isHasStrength(s)) >= 0) {
                    ++ans;
                } else {
                    break;
                }
            }
        }
        System.out.println(ans);
    }
}

class Apple implements Comparable<Apple> { // 类要比较要实现Comparable接口
    private int x, y;

    Apple(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public int compareTo(Apple o) {
        return Integer.compare(this.y, o.y);
    }

    boolean isReachable(int c) {
        return this.x <= c;
    }

    int isHasStrength(int s) {
        if (this.y <= s) {
            return s - this.y;
        } else {
            return -1;
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值