結果

問題 No.2064 Smallest Sequence on Grid
ユーザー HimaHima
提出日時 2022-10-09 18:55:12
言語 Go
(1.22.1)
結果
WA  
実行時間 -
コード長 1,538 bytes
コンパイル時間 12,542 ms
コンパイル使用メモリ 208,932 KB
実行使用メモリ 106,684 KB
最終ジャッジ日時 2023-09-05 22:18:11
合計ジャッジ時間 18,625 ms
ジャッジサーバーID
(参考情報)
judge11 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,380 KB
testcase_01 AC 1 ms
4,376 KB
testcase_02 AC 1 ms
4,504 KB
testcase_03 AC 1 ms
4,380 KB
testcase_04 AC 2 ms
4,380 KB
testcase_05 AC 1 ms
4,380 KB
testcase_06 AC 1 ms
4,384 KB
testcase_07 AC 1 ms
4,380 KB
testcase_08 WA -
testcase_09 WA -
testcase_10 WA -
testcase_11 WA -
testcase_12 WA -
testcase_13 WA -
testcase_14 WA -
testcase_15 WA -
testcase_16 WA -
testcase_17 WA -
testcase_18 WA -
testcase_19 WA -
testcase_20 AC 144 ms
106,668 KB
testcase_21 AC 143 ms
106,436 KB
testcase_22 AC 146 ms
106,436 KB
testcase_23 WA -
testcase_24 WA -
testcase_25 WA -
testcase_26 AC 145 ms
106,420 KB
testcase_27 WA -
testcase_28 AC 146 ms
106,436 KB
testcase_29 AC 117 ms
90,064 KB
testcase_30 WA -
権限があれば一括ダウンロードができます

ソースコード

diff #

package main

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

var sc = bufio.NewScanner(os.Stdin)
var out = bufio.NewWriter(os.Stdout)

func main() {
	buf := make([]byte, 1024*1024)
	sc.Buffer(buf, bufio.MaxScanTokenSize)
	sc.Split(bufio.ScanWords)

	h, w := nextInt(), nextInt()
	s := make([]string, h)
	for i := 0; i < h; i++ {
		s[i] = nextString()
	}
	ans := solve(h, w, s)
	PrintString(ans)
}

func solve(h, w int, s []string) string {
	const INF = 1 << 60
	dp := make([][]int, h)
	for i := 0; i < h; i++ {
		dp[i] = make([]int, w)
		for j := 0; j < w; j++ {
			dp[i][j] = INF
		}
	}
	dp[0][0] = int(s[0][0])
	for i := 1; i < h; i++ {
		dp[i][0] = Min(dp[i][0], dp[i-1][0]+int(s[i][0]))
	}
	for j := 1; j < w; j++ {
		dp[0][j] = Min(dp[0][j], dp[0][j-1]+int(s[0][j]))
	}
	for i := 1; i < h; i++ {
		for j := 1; j < w; j++ {
			dp[i][j] = Min(dp[i-1][j], dp[i][j-1])
			dp[i][j] += int(s[i][j])
		}
	}
	var reversed []string
	i, j := h-1, w-1
	for {
		reversed = append(reversed, string(s[i][j]))
		if i == 0 && j == 0 {
			break
		}
		if i > 0 && dp[i-1][j] == dp[i][j]-int(s[i][j]) {
			i--
		} else if j > 0 && dp[i][j-1] == dp[i][j]-int(s[i][j]) {
			j--
		}
	}
	var ans string
	for i := len(reversed) - 1; i >= 0; i-- {
		ans += reversed[i]
	}
	return ans
}

func nextInt() int {
	sc.Scan()
	i, _ := strconv.Atoi(sc.Text())
	return i
}

func nextString() string {
	sc.Scan()
	return sc.Text()
}

func PrintString(x string) {
	defer out.Flush()
	fmt.Fprintln(out, x)
}

func Min(x, y int) int {
	if x < y {
		return x
	}
	return y
}
0