3
0

問題文

解答例

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		try (Scanner scanner = new Scanner(System.in)) {
			int n = scanner.nextInt();
			int m = scanner.nextInt();
			for (int i = 0; i < m; i++) {
				int w = scanner.nextInt();
				int result = w / n * n;
				if (result == 0) {
					result = n;
				} else if ((w - result) >= (result + n - w)) {
					result += n;
				}
				System.out.println(result);
			}
		}
	}
}

補足

公式の解答例だと愚直に箱の候補を作成してどれに一番近いか、みたいなのをチェックしている。分かりやすさで言えばこれのほうが良いと思うが、箱の候補が増えていくと計算時間に問題が出てくると思うので、一応解答例では別のものを作成した。

  1. w / n * nを計算する。ひとまずこれの計算結果で箱がx * n(x + 1) * nまで絞り込める
  2. w / n * nの結果が0だった場合は(問題文の制限により0の箱には振り分けられないため)自動的に答えはnになる
  3. (w - result) >= (result + n - w)の部分でx * n(x + 1) * nのうちどちらのほうに近いかをチェックしている

ものすごいざっくりとした解説を書いたが、自分でも説明が分かりづらい。普通に公式の解答例を参考にしたほうがいいかも……

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0