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

传送门: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;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/HNUCSEE_LJK/article/details/104144916
今日推荐