1 条题解

  • 0
    @ 2024-3-27 20:22:05
    #include <iostream>
    #include <cstring>
    typedef long long ll;
    using namespace std;
    const int N = 2010;
    ll dp[N];
    bool st[N][N];
    
    int main()
    {
        int n;
        cin>>n;
        string s;
        cin>>s;
    
        //st[i][j]判断i~j是否为回文串
        for(int i = n - 1; i >= 0; i -- )
            for(int j = i; j < n; j ++ )
            {
                if(s[i] == s[j] && (j - i <= 1 || st[i + 1][j - 1]))
                    st[i][j] = 1;
            }
    
    
        for(int i = 0; i < n; i ++ )
        {
            //显然0~i是=回文串的话不需要分割
            if(st[0][i])
                dp[i] = 0;
            else
            {
                //初始化为i 最坏情况就是前i+1个需要分割i下
                dp[i] = i;
                for(int j = 0; j < i; j ++ )
                    if(st[j + 1][i])
                        dp[i] = min(dp[i], dp[j] + 1);
            }
        }
    
        cout<<dp[n - 1]<<endl;
    }
    

    信息

    ID
    569
    时间
    2000ms
    内存
    128MiB
    难度
    9
    标签
    递交数
    19
    已通过
    3
    上传者