您的位置:首页 > 其它

NYOJ 37 动态规划 回文字符串

2013-12-19 10:44 225 查看
#include<stdio.h>

#include<string.h>

#include<algorithm>

using namespace std;

/*

状态: cost[i][j] 表示要将 str 从第j个字符开始,

长度为i的子串变为回文串需要添加的字符个数.这样

转移方程为:

cost[0][i] = cost[1][i] = 0; (长度为0和长度为1的串)

当s[j] == s[i+j-1]时 ,字符串长度加2, 增加数量不变

cost[i][j] = cost[i-2][j+1];

否则

cost[i][j] = min{ cost[i-1][j], cost[i-1][j+1]}+1;

*/

int dp[1010][1010];

char str[1010];

int main()

{

int N;

scanf("%d%*c", &N);

while (N--)

{

gets(str);

int len = strlen(str);

for (int i = 0; i < len; i++)//

dp[1][i] = dp[0][i] = 0;

for (int i = 2; i <= len; i++)

for (int j = 0; j <= len-i; j++)

{

if (str[j] == str[j+i-1])

dp[i][j] = dp[i-2][j+1];

else

dp[i][j] = min(dp[i-1][j], dp[i-1][j+1]) + 1;

}

printf("%d\n", dp[len][0]);

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: