提出 #67506631


ソースコード 拡げる

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

// 経路復元のための構造体
type State struct {
	idx  int // 使用したカードのインデックス
	prev int // そのときの前の合計値
}

// main関数:標準入力を読み取り、部分和の存在判定と経路出力を行う
func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	header := strings.Split(scanner.Text(), " ")
	N, _ := strconv.Atoi(header[0])
	S, _ := strconv.Atoi(header[1])

	scanner.Scan()
	parts := strings.Split(scanner.Text(), " ")
	A := make([]int, N)
	for i := 0; i < N; i++ {
		A[i], _ = strconv.Atoi(parts[i])
	}

	// dp[sum] = State:sumを作るのにどのカードを使ったかとその前のsumを記録
	dp := make(map[int]State)
	dp[0] = State{-1, -1} // 0は何も使わずに作れる

	for i := 0; i < N; i++ {
		nextDP := make(map[int]State)
		for s := range dp { // ✅ 未使用変数stを削除
			newSum := s + A[i]
			if newSum <= S {
				if _, exists := dp[newSum]; !exists {
					nextDP[newSum] = State{i, s}
				}
			}
		}
		for k, v := range nextDP {
			dp[k] = v
		}
	}

	if _, ok := dp[S]; !ok {
		fmt.Println(-1)
		return
	}

	// 経路復元
	res := []int{}
	curr := S
	for curr != 0 {
		state := dp[curr]
		res = append(res, state.idx+1) // 1-indexed
		curr = state.prev
	}

	// 逆順にして出力
	for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
		res[i], res[j] = res[j], res[i]
	}

	fmt.Println(len(res))
	for i, v := range res {
		if i > 0 {
			fmt.Print(" ")
		}
		fmt.Print(v)
	}
	fmt.Println()
}

提出情報

提出日時
問題 B18 - Subset Sum with Restoration
ユーザ myoshizumi
言語 Go (go 1.20.6)
得点 1000
コード長 1656 Byte
結果 AC
実行時間 8 ms
メモリ 2812 KiB

ジャッジ結果

セット名 Sample All
得点 / 配点 0 / 0 1000 / 1000
結果
AC × 3
AC × 21
セット名 テストケース
Sample sample_01.txt, sample_02.txt, sample_03.txt
All large_01.txt, large_02.txt, large_03.txt, large_04.txt, large_05.txt, max_01.txt, max_02.txt, max_03.txt, sample_01.txt, sample_02.txt, sample_03.txt, small_01.txt, small_02.txt, small_03.txt, small_04.txt, small_05.txt, small_06.txt, small_07.txt, small_08.txt, small_09.txt, small_10.txt
ケース名 結果 実行時間 メモリ
large_01.txt AC 7 ms 2276 KiB
large_02.txt AC 6 ms 2812 KiB
large_03.txt AC 1 ms 1628 KiB
large_04.txt AC 1 ms 1608 KiB
large_05.txt AC 8 ms 2640 KiB
max_01.txt AC 1 ms 1624 KiB
max_02.txt AC 1 ms 1612 KiB
max_03.txt AC 1 ms 1624 KiB
sample_01.txt AC 1 ms 1568 KiB
sample_02.txt AC 1 ms 1564 KiB
sample_03.txt AC 1 ms 1604 KiB
small_01.txt AC 1 ms 1624 KiB
small_02.txt AC 1 ms 1620 KiB
small_03.txt AC 1 ms 1568 KiB
small_04.txt AC 1 ms 1576 KiB
small_05.txt AC 1 ms 1572 KiB
small_06.txt AC 1 ms 1576 KiB
small_07.txt AC 1 ms 1620 KiB
small_08.txt AC 1 ms 1568 KiB
small_09.txt AC 1 ms 1572 KiB
small_10.txt AC 1 ms 1600 KiB