Submission #67625944


Source Code Expand

package main

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

// longestPalindromicSubsequence は、与えられた文字列 S に対して、削除のみで構成可能な
// 最長の回文部分列の長さを返します。
// パラメータ:
//   - s string : 英小文字からなる入力文字列(長さ N)
// 戻り値:
//   - int : 最長の回文部分列の長さ
func longestPalindromicSubsequence(s string) int {
	n := len(s)

	// dp[i][j] := s[i..j] の最長回文部分列の長さ
	dp := make([][]int, n)
	for i := range dp {
		dp[i] = make([]int, n)
	}

	// 長さ1の部分列は常に回文
	for i := 0; i < n; i++ {
		dp[i][i] = 1
	}

	// 長さ2以上の部分列についてのDP
	for length := 2; length <= n; length++ {
		for i := 0; i <= n-length; i++ {
			j := i + length - 1
			if s[i] == s[j] {
				if length == 2 {
					dp[i][j] = 2
				} else {
					dp[i][j] = dp[i+1][j-1] + 2
				}
			} else {
				if dp[i+1][j] > dp[i][j-1] {
					dp[i][j] = dp[i+1][j]
				} else {
					dp[i][j] = dp[i][j-1]
				}
			}
		}
	}

	return dp[0][n-1]
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	// 入力 N は使用しないが、読み取りだけ行う
	_ = scanner.Text()

	scanner.Scan()
	s := strings.TrimSpace(scanner.Text())

	result := longestPalindromicSubsequence(s)
	fmt.Println(result)
}

Submission Info

Submission Time
Task B21 - Longest Subpalindrome
User myoshizumi
Language Go (go 1.20.6)
Score 1000
Code Size 1412 Byte
Status AC
Exec Time 7 ms
Memory 8188 KiB

Judge Result

Set Name Sample All
Score / Max Score 0 / 0 1000 / 1000
Status
AC × 2
AC × 25
Set Name Test Cases
Sample sample_01.txt, sample_02.txt
All in01.txt, in02.txt, in03.txt, in04.txt, in05.txt, in06.txt, in07.txt, in08.txt, in09.txt, in10.txt, in11.txt, in12.txt, in13.txt, in14.txt, in15.txt, in16.txt, in17.txt, in18.txt, in19.txt, in20.txt, in21.txt, in22.txt, in23.txt, sample_01.txt, sample_02.txt
Case Name Status Exec Time Memory
in01.txt AC 0 ms 1612 KiB
in02.txt AC 0 ms 1612 KiB
in03.txt AC 0 ms 1612 KiB
in04.txt AC 0 ms 1608 KiB
in05.txt AC 0 ms 1612 KiB
in06.txt AC 0 ms 1720 KiB
in07.txt AC 1 ms 1996 KiB
in08.txt AC 1 ms 2464 KiB
in09.txt AC 1 ms 2948 KiB
in10.txt AC 2 ms 3704 KiB
in11.txt AC 2 ms 4520 KiB
in12.txt AC 3 ms 5740 KiB
in13.txt AC 4 ms 6608 KiB
in14.txt AC 5 ms 7736 KiB
in15.txt AC 6 ms 8184 KiB
in16.txt AC 6 ms 8188 KiB
in17.txt AC 7 ms 8188 KiB
in18.txt AC 7 ms 8188 KiB
in19.txt AC 0 ms 1620 KiB
in20.txt AC 5 ms 8180 KiB
in21.txt AC 5 ms 8184 KiB
in22.txt AC 5 ms 8184 KiB
in23.txt AC 5 ms 8184 KiB
sample_01.txt AC 0 ms 1612 KiB
sample_02.txt AC 0 ms 1620 KiB