uva 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
大意:
给你一个字符串,让你随便插入字符,问你最少插入多少个字符能使得字符串变成回文串,并打印出任意一个字符串。

#include <bits/stdc++.h>

using namespace std;
//fstream in,out;
int dp[1001][1001],len;
string s;
void GetString(int i,int j)
{
    if(i>j)
        return;
    if(i==j)
    {
        cout<<s[i-1];
        return;
    }
    if(s[i-1]==s[j-1])
    {
        cout<<s[i-1];
        GetString(i+1,j-1);
        cout<<s[i-1];//
    }
    else
    {
        if(dp[i][j]==dp[i+1][j]+1)
        {
            cout<<s[i-1];
            GetString(i+1,j);
            cout<<s[i-1];
        }
        else
        {
            cout<<s[j-1];
            GetString(i,j-1);
            cout<<s[j-1];
        }
    }
}

int main()
{
    ios::sync_with_stdio(false);
    while(cin>>s)
    {
        len=s.size();
        for(int l=2;l<=len;l++)
        {
            for(int i=0;i<=len-l+1;i++)
            {
                int j=i+l-1;
                if(s[i-1]==s[j-1])
                    dp[i][j]=dp[i+1][j-1];
                else
                    dp[i][j]=min(dp[i][j-1],dp[i+1][j])+1;
            }
        }
        cout<<dp[1][len]<<" ";
        GetString(1,len);
        cout<<endl;
    }
    return 0;
}

解答:
用动态规划的思想来求解,首先设置dp[i][j]表示第i个字符到第j个字符形成回文串最少需要插入的字符个数。
接下来状态转移,如果第i个字符和第j个字符相同,那么dp[i][j]=dp[i+1][j-1],此时不需要插入任何字符。
如果第i个字符和第j个字符不相同,那么dp[i][j]=min(dp[i+1][j],dp[i][j-1])+1,方程的含义为比较第i+1个字符到第j个字符之间形成回文串需要插入最少字符个数与第i个字符到第j-1个字符之间形成回文串需要插入最少字符的个数,如果dp[i+1][j]小于dp[i][j-1],此时可以在第j个字符后面插入一个和s[i]相同的字符用来形成回文串,同理。如果dp[i][j-1]小于或者等于dp[i+1][j],可以在i的前面插入一个和s[j]相同的字符串。

最后注意打印路径即可。

你可能感兴趣的:(uva)