ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป ๋ฌธ์ œ

 

9465๋ฒˆ: ์Šคํ‹ฐ์ปค

์ฒซ์งธ ์ค„์— ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์˜ ๊ฐœ์ˆ˜ T๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์˜ ์ฒซ์งธ ์ค„์—๋Š” n (1 ≤ n ≤ 100,000)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ ๋‘ ์ค„์—๋Š” n๊ฐœ์˜ ์ •์ˆ˜๊ฐ€ ์ฃผ์–ด์ง€๋ฉฐ, ๊ฐ ์ •์ˆ˜๋Š” ๊ทธ ์œ„์น˜์— ํ•ด๋‹นํ•˜๋Š” ์Šคํ‹ฐ์ปค์˜

www.acmicpc.net


โœ๐Ÿป ํ’€์ด

๐ŸŽจ Go

// https://www.acmicpc.net/problem/9465
package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
)

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	var t int
	fmt.Fscanln(reader, &t)
	for i := 0; i < t; i++ {
		var n int
		fmt.Fscanln(reader, &n)
		var scores = make([][]int, 2)
		var dp = make([][]int, 2)
		for j := 0; j < 2; j++ {
			scores[j] = make([]int, n)
			dp[j] = make([]int, n)
			for k := 0; k < n; k++ {
				fmt.Fscanf(reader, "%d ", &scores[j][k])
			}
		}
		dp[0][0] = scores[0][0]
		dp[1][0] = scores[1][0]
		for j := 1; j < n; j++ {
			if j == 1 {
				dp[0][j] = dp[1][j-1] + scores[0][j]
				dp[1][j] = dp[0][j-1] + scores[1][j]
			} else {
				dp[0][j] = int(math.Max(float64(dp[1][j-1]), float64(dp[1][j-2]))) + scores[0][j]
				dp[1][j] = int(math.Max(float64(dp[0][j-1]), float64(dp[0][j-2]))) + scores[1][j]
			}
		}
		fmt.Fprintln(writer, int(math.Max(float64(dp[0][n-1]), float64(dp[1][n-1]))))
	}
}

๐ŸŽจ Python3

# https://www.acmicpc.net/problem/9465
import sys

if __name__ == "__main__":
    t = int(sys.stdin.readline())
    for i in range(t):
        n = int(sys.stdin.readline())
        scores = []
        dp = [[0]*n for _ in range(2)]
        for j in range(2):
            scores.append(list(map(int, sys.stdin.readline().split())))
        dp[0][0] = scores[0][0]
        dp[1][0] = scores[1][0]
        for j in range(1, n):
            if j == 1:
                dp[0][j] = dp[1][j-1] + scores[0][j]
                dp[1][j] = dp[0][j-1] + scores[1][j]
            else:
                dp[0][j] = max(dp[1][j-1], dp[1][j-2]) + scores[0][j]
                dp[1][j] = max(dp[0][j-1], dp[0][j-2]) + scores[1][j]
        print(max(dp[0][n-1], dp[1][n-1]))
728x90
๋Œ“๊ธ€