HDU 1513 Palindrome

时间:2023-03-08 22:52:20
HDU 1513 Palindrome

题目就是给一个字符串问最少插入多少个字符能让原字符串变为回文字符串。

算法:

用原串的长度减去原串与翻转后的串的最大公共字串的长度,就是所求答案。

 //#define LOCAL
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstring>
using namespace std; const int maxn = + ;
char s1[maxn], s2[maxn];
int dp[][maxn]; void Reverse(char str[], int len)
{
int i, t;
for(i = ; i < len/; ++i)
{
t = str[i];
str[i] = str[len - - i];
str[len - - i] = t;
}
} int main(void)
{
#ifdef LOCAL
freopen("1513in.txt", "r", stdin);
#endif
int len;
while(scanf("%d", &len) == )
{
scanf("%s", s1);
memcpy(s2, s1, sizeof(s1));
Reverse(s2, len);
int i, j;
memset(dp, , sizeof(dp));
int cur = ,ans;
for(i = ; i <= len; ++i)
{
for(j = ; j <= len; ++j)
{
if(s1[i-] == s2[j-])
dp[cur][j] = dp[-cur][j-] + ;
else
dp[cur][j] = max(dp[-cur][j], dp[cur][j-]);
}
cur = - cur;
}
ans = len - dp[len&][len];
printf("%d\n", ans);
}
return ;
}

代码君