UVa 10617 - Again Palindrome

来源:互联网 发布:淘宝店铺交易数据分析 编辑:程序博客网 时间:2024/05/21 22:48

字符串的DP,用d[i][j] 表示 i和j ( i < j ) 之间有多少个回文的字符串。

所以有两种情况 当 str [i] == str[j] 时 的d[i][j] >?= dp ( i + 1, j ) + dp ( i, j - 1 ) + 1.

当str[i] != str[j] 时 d[i][j] >?= dp ( i +1, j ) + dp ( i, j - 1 ) - dp ( i + 1, j - 1 ) ( 要注意 i + 1 ~ j 和 i ~ j - 1 计算了两遍 i + 1 ~ j - 1 ,所以要减去 )

 

#include <iostream>#include <cstdio>#include <string>#include <cstring>#include <algorithm>const int INF = 1 << 30;using namespace std;int Case;long long d[65][65];string str;long long dp ( int i, int j ) {    long long &ans = d[i][j];    if ( ans != -1 ) return ans;    ans = -1 << 30;    if ( i >= j ) {        if ( j == i ) return ans = 1;        else return ans = 0;    }    else {        if ( str[i] == str[j] ) ans = max ( ans, dp ( i + 1, j ) + dp ( i, j - 1 ) + 1 );        else ans = max ( ans, dp ( i + 1, j ) + dp ( i, j - 1 ) - dp ( i + 1, j - 1 ) );    }    return ans;}int main ( ) {    cin >> Case;    while ( Case-- ) {        cin >> str;        int len = str.length ( );        memset ( d, -1, sizeof ( d ) );        cout << dp ( 0, len - 1 ) << endl;    }    return 0;}


 

原创粉丝点击