0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ABC - 102- A&B&C

Posted at

AtCoder ABC 102 A&B&C

AtCoder - 102

A問題

  • 2とNどちらでも割り切れる整数
    • 入力値Nが2で割り切れる
      • そのまま出力
    • 2で割り切れない場合はNを2倍する
      • 2倍すれば2で割り切れるしNで割りきれる
	private void solveA() {
		Scanner scanner = null;
		int numN = 0;

		try {
			scanner = new Scanner(System.in);
			numN = scanner.nextInt();

			if (numN % 2 == 0) {
				System.out.println(numN);
			} else {
				System.out.println(numN * 2);
			}

			System.out.println("");

		} finally {
			if (scanner != null) {
				scanner.close();
			}
		}
	}

B問題

  • 入力値をソートして、入力値の最小と最大の差をとれば添え字の異なる数値の差が最大
    • 最小値と最大値の添え字は異なるので。。。
	private void solveB() {
		Scanner scanner = null;
		int numN = 0;

		try {
			scanner = new Scanner(System.in);
			numN = scanner.nextInt();
			int[] wk = new int[numN];

			for (int i = 0; i < wk.length; i++) {
				wk[i] = scanner.nextInt();
			}
			Arrays.sort(wk);

			System.out.println(wk[wk.length - 1] - wk[0]);

			System.out.println("");

		} finally {
			if (scanner != null) {
				scanner.close();
			}
		}
	}

C問題

  • $abs(A_1−(b+1))+abs(A_2−(b+2))+...+abs(A_N−(b+N))$

  • ⅰ) $abs(xi-a)$ の総和(aとの距離の総和)を最小にするのは中央値

    • $Bi = A_i − i$ と定義すれば、問題は、自由に整数 b を選び、$abs(Bi − b)$ の総和を最小化する問題
    • bを最小にするために、$(A_i − i)$ の中央値をとる
  • ⅱ) $(xi-a)^2$ の総和を最小にするのは平均値


	/**
	 * ⅰ)abs(xi-a)の総和(aとの距離の総和)を最小にするのは中央値で、
	 * ⅱ)(xi-a)^2の総和を最小にするのは平均値
	 */
	private void solveC() {
		Scanner scanner = null;
		int numN = 0;

		try {
			scanner = new Scanner(System.in);
			numN = scanner.nextInt();
			int[] wk = new int[numN];

			for (int i = 0; i < wk.length; i++) {
				wk[i] = scanner.nextInt();
			}

			int[] wkWk = new int[numN];
			for (int i = 0; i < numN; i++) {
				/*
				 * b=(Xi-a)
				 * a=(i+1)
				 */
				wkWk[i] = wk[i] - (i + 1);
			}
			Arrays.sort(wkWk);

			int b = 0;
			if (numN % 2 == 0) {
				b = wkWk[numN / 2 - 1];
			} else {
				b = wkWk[numN / 2];
			}

			long res = 0;

			for (int i = 0; i < numN; i++) {
				res += Math.abs(wkWk[i] - b);
			}
			System.out.println(res);

		} finally {
			if (scanner != null) {
				scanner.close();
			}
		}
	}

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?