51Nod 1092 回文字符串(LCS跟dp)
2018-03-13 19:28
483 查看
1092 回文字符串
基准时间限制:1 秒 空间限制:131072 KB 分值: 10 难度:2级算法题
收藏
关注 回文串是指aba、abba、cccbccc、aaaa这种左右对称的字符串。每个字符串都可以通过向中间添加一些字符,使之变为回文字符串。例如:abbc 添加2个字符可以变为 acbbca,也可以添加3个变为 abbcbba。方案1只需要添加2个字符,是所有方案中添加字符数量最少的。 Input
#include <cstring>
using namespace std;
const int MAXN = 1001;
int dp[MAXN][MAXN];
char sOne[MAXN];
char sTwo[MAXN];
int main()
{
while(cin >> sOne)
{
int i, j;
int len = (int)strlen(sOne);
// 倒置
for (i = len - 1, j = 0; i >= 0; i--, j++)
{
sTwo[j] = sOne[i];
}
for (i = 1; i <= len; i++)
{
for (j = 1;j <= len;j++)
{
if (sOne[i - 1] == sTwo[j - 1])
{
dp[i][j] = dp[i - 1][j - 1] + 1;
}
else
{
dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]);
}
}
}
cout << len - dp[len][len] << endl;
}
return 0;
}
基准时间限制:1 秒 空间限制:131072 KB 分值: 10 难度:2级算法题
收藏
关注 回文串是指aba、abba、cccbccc、aaaa这种左右对称的字符串。每个字符串都可以通过向中间添加一些字符,使之变为回文字符串。例如:abbc 添加2个字符可以变为 acbbca,也可以添加3个变为 abbcbba。方案1只需要添加2个字符,是所有方案中添加字符数量最少的。 Input
输入一个字符串Str,Str的长度 <= 1000。Output
输出最少添加多少个字符可以使之变为回文字串。Input示例
abbcOutput示例
2#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 1001;
int dp[MAXN][MAXN];
char sOne[MAXN];
char sTwo[MAXN];
int main()
{
while(cin >> sOne)
{
int i, j;
int len = (int)strlen(sOne);
// 倒置
for (i = len - 1, j = 0; i >= 0; i--, j++)
{
sTwo[j] = sOne[i];
}
for (i = 1; i <= len; i++)
{
for (j = 1;j <= len;j++)
{
if (sOne[i - 1] == sTwo[j - 1])
{
dp[i][j] = dp[i - 1][j - 1] + 1;
}
else
{
dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]);
}
}
}
cout << len - dp[len][len] << endl;
}
return 0;
}
相关文章推荐
- 51nod 1092 回文字符串 LCS 或 区间dp
- 51Nod 1092 回文字符串(LCS跟dp)
- 51nod 1092 回文字符串 (LCS_DP)
- 51nod 1092 回文字符串 dp问题
- 【51nod】--1092 回文字符串 (字符串LCS)
- 【51Nod】1092 - 回文字符串(LCS)
- LCS-51NOD-1092 回文字符串
- 51nod 1092 回文字符串 【巧用 dp】
- 【51nod 1092】 回文字符串(区间DP)
- 51NOD 1092 回文字符串 LCS
- 51nod 1092 回文字符串 (dp)
- 51nod 1092 回文字符串(LCS)
- 51nod 1092 回文字符串(区间dp)
- 51Nod 1092 回文字符串 | 最长公共子序列变形
- 51nod 1092 回文字符串
- nyoj 37 回文字符串 【lcs&&dp】
- 51nod 1092 回文字符串 (添加几个变成回文)
- 51nod 1092 回文字符串
- nyoj 37 51nod oj 1092 回文字符串 【LCS变形】
- 51nod-【1092 回文字符串】