编辑代码

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int A = scanner.nextInt();
        int B = scanner.nextInt();
        int C = scanner.nextInt();
        int D = scanner.nextInt();
        int N = scanner.nextInt();

        int[] result = findSolution(A, B, C, D, N);
        if (result == null) {
            System.out.println(-1);
        } else {
            System.out.println(result[0] + " " + result[1] + " " + result[2] + " " + result[3]);
        }
    }

    private static int[] findSolution(int A, int B, int C, int D, int N) {
        // 遍历x, y, z,计算w是否符合条件
        for (int x = 0; x <= 2500; x++) {
            for (int y = 0; y <= 2500; y++) {
                long remaining = N - (long)A * x - (long)B * y;
                if (remaining < 0) {
                    break; // 由于y在增加,remaining会越来越小,可以直接跳出
                }
                for (int z = 0; z <= 2500; z++) {
                    long rem = remaining - (long)C * z;
                    if (rem < 0) {
                        break; // 同理,z增加时rem减少,跳出
                    }
                    if (rem % D == 0) {
                        int w = (int)(rem / D);
                        if (w >= 0 && w <= 2500) {
                            return new int[]{x, y, z, w};
                        }
                    }
                }
            }
        }
        return null;
    }
}