結果

問題 No.4 おもりと天秤
ユーザー maruyuki95
提出日時 2020-07-05 21:24:58
言語 Java
(openjdk 23)
結果
TLE  
実行時間 -
コード長 1,619 bytes
コンパイル時間 2,772 ms
コンパイル使用メモリ 83,272 KB
実行使用メモリ 66,808 KB
最終ジャッジ日時 2024-09-22 22:00:29
合計ジャッジ時間 12,392 ms
ジャッジサーバーID
(参考情報)
judge3 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 18 TLE * 1 -- * 4
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

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 halfTotalWeight = totalWeight /2 ;
		return canMakeWeight(convertToList(weights), halfTotalWeight);
	}

	private boolean canMakeWeight(List<Integer> weights, int goalWeight) {
		List<Integer> copyList = new ArrayList<>(weights);
		
		for (Integer weight : weights) {
			if (weight == goalWeight) {
				return true;
			} 
			
			
			copyList.remove(weight);
			if (weight > goalWeight) {
				continue;
			}
			
			if (canMakeWeight(copyList, goalWeight - weight)) {
				return true;
			}
		}
		return false;
	}

	private List<Integer> convertToList(int[] array) {
		List<Integer> ret = new ArrayList<>();
		for (int i : array) {
			ret.add(i);
		}
		return ret ;
	}
	
	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