10453 - Make Palindrome
By definition palindrome is a string which is not changed when reversed. “MADAM” is a nice example of
palindrome. It is an easy job to test whether a given string is a palindrome or not. But it may not be
so easy to generate a palindrome.
Here we will make a palindrome generator which will take an input string and return a palindrome.
You can easily verify that for a string of length n, no more than (n−1) characters are required to make
it a palindrome. Consider ‘abcd’ and its palindrome ‘abcdcba’ or ‘abc’ and its palindrome ‘abcba’.
But life is not so easy for programmers!! We always want optimal cost.
And you have to find the minimum number of characters required to make a given string to a
palindrome if you are allowed to insert characters at any position of the string.
Input
Each input line consists only of lower case letters. The size of input string will be at most 1000. Input
is terminated by EOF.
Output
For each input print the minimum number of characters and such a palindrome separated by one space
in a line. There may be many such palindromes. Any one will be accepted.
Sample Input
abcd
aaaa
abc
aab
abababaabababa
pqrsabcdpqrs
Sample Output
3 abcdcba
0 aaaa
2 abcba
1 baab
0 abababaabababa
9 pqrsabcdpqrqpdcbasrqp
题目大意:给一个字符串,可以增加插入字符,问变成回文串的最小步数和最后的回文串
ac代码
16444182 | 10453 | Make Palindrome | Accepted | C++ | 0.175 | 2015-11-16 08:17:18 |
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<stdlib.h>
#define INF 0x3f3f3f3f
using namespace std;
int dp[1010][1010];
int flag[1010][1010];
char str[1010];
void DP()
{
int len=strlen(str+1);
int i,j;
for(i=len;i>=1;i--)
{
for(j=i+1;j<=len;j++)
{
if(str[i]==str[j])
dp[i][j]=dp[i+1][j-1];
else
{
if(dp[i+1][j]<dp[i][j-1])
{
dp[i][j]=dp[i+1][j]+1;
flag[i][j]=-1;
}
else
{
dp[i][j]=dp[i][j-1]+1;
flag[i][j]=1;
}
}
}
}
}
void print(int a,int b)
{
if(a>b)
return;
if(a==b)
{
printf("%c",str[a]);
}
else
if(flag[a][b]==0)
{
printf("%c",str[a]);
print(a+1,b-1);
printf("%c",str[a]);
}
else
{
if(flag[a][b]==-1)
{
printf("%c",str[a]);
print(a+1,b);
printf("%c",str[a]);
}
else
{
printf("%c",str[b]);
print(a,b-1);
printf("%c",str[b]);
}
}
}
int main()
{
while(scanf("%s",str+1)!=EOF)
{
int len=strlen(str+1);
int i,j;
memset(flag,0,sizeof(flag));
DP();
printf("%d ",dp[1][len]);
print(1,len);
printf("\n");
}
}