BOJ 1509 팰린드롬 분할

Jmnote (토론 | 기여)님의 2024년 2월 1일 (목) 23:48 판 (새 문서: ==개요== {{BOJ |단계= 47 |분류1= 다이나믹 프로그래밍 }} ==C++== <syntaxhighlight lang='cpp'> #include <bits/stdc++.h> using namespace std; int main() { string s;...)
(차이) ← 이전 판 | 최신판 (차이) | 다음 판 → (차이)

1 개요[ | ]

BOJ 1509 팰린드롬 분할

2 C++[ | ]

#include <bits/stdc++.h>
using namespace std;

int main() {
    string s;
    cin >> s;
    int n = s.length();
    vector<int> dp(n + 1, 0);
    vector<vector<bool>> pal(n, vector<bool>(n, false));

    for (int i = 0; i < n; ++i) {
        pal[i][i] = true; // 한 글자는 항상 팰린드롬
        dp[i + 1] = i + 1; // 최악의 경우: 모든 문자를 개별적으로 분할
    }

    for (int len = 2; len <= n; ++len) {
        for (int i = 0; i <= n - len; ++i) {
            int j = i + len - 1;
            if (s[i] == s[j] && (len == 2 || pal[i + 1][j - 1])) {
                pal[i][j] = true;
            }
        }
    }

    for (int i = 1; i <= n; ++i) {
        for (int j = 0; j < i; ++j) {
            if (pal[j][i - 1]) {
                dp[i] = min(dp[i], dp[j] + 1);
            }
        }
    }
    cout << dp[n];
}
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}