結果

問題 No.4 おもりと天秤
ユーザー seiichiseiichi
提出日時 2021-01-21 14:34:58
言語 Go
(1.22.1)
結果
AC  
実行時間 3 ms / 5,000 ms
コード長 1,431 bytes
コンパイル時間 10,510 ms
コンパイル使用メモリ 213,272 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-08-26 01:37:50
合計ジャッジ時間 11,687 ms
ジャッジサーバーID
(参考情報)
judge12 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,376 KB
testcase_01 AC 1 ms
4,376 KB
testcase_02 AC 1 ms
4,380 KB
testcase_03 AC 1 ms
4,380 KB
testcase_04 AC 1 ms
4,376 KB
testcase_05 AC 2 ms
4,376 KB
testcase_06 AC 1 ms
4,376 KB
testcase_07 AC 3 ms
4,376 KB
testcase_08 AC 1 ms
4,376 KB
testcase_09 AC 3 ms
4,380 KB
testcase_10 AC 3 ms
4,376 KB
testcase_11 AC 1 ms
4,380 KB
testcase_12 AC 1 ms
4,376 KB
testcase_13 AC 1 ms
4,380 KB
testcase_14 AC 1 ms
4,380 KB
testcase_15 AC 1 ms
4,380 KB
testcase_16 AC 1 ms
4,380 KB
testcase_17 AC 1 ms
4,380 KB
testcase_18 AC 2 ms
4,380 KB
testcase_19 AC 2 ms
4,376 KB
testcase_20 AC 2 ms
4,376 KB
testcase_21 AC 2 ms
4,380 KB
testcase_22 AC 2 ms
4,380 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

package main

import "fmt"

func scan() (N int, W []int) {
	fmt.Scan(&N)
	for i := 0; i < N; i++ {
		var w int
		fmt.Scan(&w)
		W = append(W, w)
	}
	return
}

func main() {
	N, W := scan()
	// N, W := 3, []int{1, 2, 3}
	// N, W := 15, []int{62, 8, 90, 2, 24, 62, 38, 64, 76, 60, 30, 76, 80, 74, 72}
	// N, W := 15, []int{69, 81, 52, 89, 73, 67, 17, 87, 38, 96, 16, 64, 50, 66, 97}

	var sum int
	for _, w := range W {
		sum += w
	}

	var expectedWeight int
	res := "impossible"

	if sum%2 != 0 {
		// 割り切れない場合は水平にならない
		fmt.Print(res)
		return
	} else {
		expectedWeight = sum / 2
	}

	// すべての組み合わせを計算するとO(2^N)となってしまう
	// 動的計画法を使って、Nが2から100のすべてのパターンにおいて、可能性のある数値の組み合わせを順番にマッピングしていく
	// どこかでexpectedWeightと一致する値が見つかればそこで終了するようにする
	// こうすることで、O(N*W*W)となる
	// N=100, W=100で考えてみると
	// 1.2676506e+30 (2^N) vs 100,000(N*W*W) で歴然

	var dp [100][100*100 + 1]bool

	dp[0][0] = true
	dp[0][W[0]] = true

	for i := 1; i < N; i++ {
		dp[i][W[i]] = true
		for j := 0; j < len(dp[i-1]); j++ {
			if dp[i-1][j] {
				dp[i][j] = true
				dp[i][j+W[i]] = true
			}
		}
		if dp[N-1][expectedWeight] {
			res = "possible"
			goto Exit
		}
	}
Exit:
	fmt.Print(res)
}
0