結果

問題 No.4 おもりと天秤
ユーザー maruyuki95maruyuki95
提出日時 2020-07-07 22:40:48
言語 Java21
(openjdk 21)
結果
AC  
実行時間 182 ms / 5,000 ms
コード長 1,696 bytes
コンパイル時間 1,934 ms
コンパイル使用メモリ 78,624 KB
実行使用メモリ 57,152 KB
最終ジャッジ日時 2024-04-09 21:17:54
合計ジャッジ時間 5,749 ms
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 96 ms
52,756 KB
testcase_01 AC 99 ms
53,060 KB
testcase_02 AC 110 ms
53,156 KB
testcase_03 AC 100 ms
53,068 KB
testcase_04 AC 110 ms
54,108 KB
testcase_05 AC 173 ms
57,096 KB
testcase_06 AC 98 ms
52,816 KB
testcase_07 AC 167 ms
56,800 KB
testcase_08 AC 116 ms
53,952 KB
testcase_09 AC 115 ms
53,488 KB
testcase_10 AC 179 ms
56,800 KB
testcase_11 AC 111 ms
54,088 KB
testcase_12 AC 116 ms
56,200 KB
testcase_13 AC 115 ms
53,928 KB
testcase_14 AC 113 ms
54,116 KB
testcase_15 AC 104 ms
53,012 KB
testcase_16 AC 114 ms
53,860 KB
testcase_17 AC 104 ms
53,028 KB
testcase_18 AC 182 ms
57,064 KB
testcase_19 AC 168 ms
56,800 KB
testcase_20 AC 171 ms
57,088 KB
testcase_21 AC 161 ms
56,968 KB
testcase_22 AC 167 ms
57,152 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;

public class Main {

	public static void main(String[] args) {
		new Main().execute();
	}

	private void execute() {
		int[] weights = loadInputValue();
		outputResult(canDevideInHalf(weights));
	}

	boolean canDevideInHalf(int[] weights) {
		int totalWeight = total(weights);
		if (totalWeight % 2 != 0) {
			return false;
		}

		int goalWeight = totalWeight / 2;
		return canMakeWeight(weights, goalWeight);
	}

	private boolean canMakeWeight(int[] weights, int goalWeight) {
		Set<Integer> makableWeights = new HashSet<>();
		makableWeights.add(0);
		for (Integer weight : weights) {
			Set<Integer> additionalWeights = new HashSet<>(makableWeights);
			for (Integer makableWeight : makableWeights) {
				int additionalWeight = makableWeight + weight;
				if (additionalWeight == goalWeight) {
					return true;
				} else if (additionalWeight > goalWeight) {
					continue;
				} 
				additionalWeights.add(additionalWeight); 
			}
			makableWeights = additionalWeights;
		}
		return false;
	}

	private int total(int[] values) {
		int totalValue = 0;
		for (int value : values) {
			totalValue += value;
		}
		return totalValue;
	}

	@SuppressWarnings("resource")
	private int[] loadInputValue() {
		Scanner sc = new Scanner(System.in);
		int[] ret = new int[sc.nextInt()];
		for (int i = 0; i < ret.length; i++) {
			ret[i] = sc.nextInt();
		}
		return ret;
	}

	private void outputResult(boolean canDevideInHalf) {
		if (canDevideInHalf) {
			System.out.println("possible");
		} else {
			System.out.println("impossible");
		}
	}

}
0