UVA 11584Partitioning by Palindromes

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UVA 11584Partitioning by Palindromes相关的知识,希望对你有一定的参考价值。

题解:

最先想到的是区间dp。。。但是n的范围是到1000,超时

后来看了题解。发现用一维DP即可

dp[j]表示从1到j组成的最小回文字符串个数

dp[j] = min( dp[i] + 1 ) s[i + 1 ,j]为回文字符串

代码:

#include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define se second
#define fs first
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define pii pair<int,int>
#define ll long long
using namespace std;
const int maxn = 1500;
int dp[ maxn ], p[ maxn ][  maxn ];
char str[ maxn ];
int n;
int isp( int i ,int j )
{
    int& ans = p[ i ][ j ];
    if( ans >= 0 ) return ans;
    if( i >= j ) return ans = 1;
    if( str[ i ] == str[ j ] ) return  ans = isp( i + 1, j - 1);
    return ans = 0;
}
int main()
{
    int T;
    scanf( "%d", &T );
    while( T -- )
    {
        scanf( "%s", str + 1 );
        n = strlen( str + 1 );
        memset( p, -1, sizeof( p ) );
        for( int i = 0; i <= n; i ++ ) dp[ i ] = i;
        for( int i = 2; i <= n; i ++ )
        for( int j = 1; j <= i; j ++ )
        if( isp( j, i ) ) dp[ i ] = min( dp[ i ], dp[ j - 1 ] + 1 );
        printf( "%d\n", dp[ n ] );
    }
    return 0;
}

 

以上是关于UVA 11584Partitioning by Palindromes的主要内容,如果未能解决你的问题,请参考以下文章

UVA11584-Partitioning by Palindromes(动态规划基础)

题解UVA11584 Partitioning by Palindromes

uva 11584 Partitioning by Palindromes 线性dp

UVA 11584Partitioning by Palindromes

UVA11584 Partitioning by Palindromes

Partitioning by Palindromes UVA - 11584