Codeforces ZeptoLab Code Rush 2015 C: Om Nom and Candies

解法

yukicoder No. 176 の解法がまるごと流用できる。

kenkoooo.hatenablog.com

コード

import java.io.IOException;

public class Main {

	public static void main(String[] args) {
		long C = nextInt();
		long H1 = nextInt();
		long H2 = nextInt();
		long W1 = nextInt();
		long W2 = nextInt();

		long happiness = 0;
		/*
		 * Wが大きい方をredにする
		 */

		long Wr = W1;
		long Wb = W2;
		long Hr = H1;
		long Hb = H2;
		if (W1 < W2) {
			Wr = W2;
			Wb = W1;
			Hr = H2;
			Hb = H1;
		}
		if (Wr >= 1000) {
			for (long i = 0;; i++) {
				if (Wr * i > C) {
					break;
				}
				long j = (C - Wr * i) / Wb;
				long next = Hr * i + Hb * j;

				happiness = Math.max(happiness, next);
			}
			System.out.println(happiness);
		} else {
			for (long i = 0;; i++) {
				if (Wr * i > C || i > Wb) {
					break;
				}
				long j = (C - Wr * i) / Wb;
				long next = Hr * i + Hb * j;

				happiness = Math.max(happiness, next);
			}
			for (long i = 0;; i++) {
				if (Wb * i > C || i > Wr) {
					break;
				}
				long j = (C - Wb * i) / Wr;
				long next = Hb * i + Hr * j;

				happiness = Math.max(happiness, next);
			}
			System.out.println(happiness);
		}

	}

	static int nextInt() {
		int c;
		try {
			c = System.in.read();
			while (c != '-' && (c < '0' || c > '9'))
				c = System.in.read();
			if (c == '-')
				return -nextInt();
			int res = 0;
			while (c >= '0' && c <= '9') {
				res = res * 10 + c - '0';
				c = System.in.read();
			}
			return res;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return -1;
	}
}