您的位置:首页 > 其它

Make Palindrome - UVa 10453 dp

2014-08-01 00:28 323 查看
Problem A
Make Palindrome
Input: standard input
Output: standard output
Time Limit: 8 seconds


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 seperated by one space in a line. There may be many such palindromes. Any one will be accepted.

Sample Input

abcdaaaaabcaababababaabababapqrsabcdpqrs


Sample Output

3 abcdcba0 aaaa2 abcba1 baab0 abababaabababa9 pqrsabcdpqrqpdcbasrqp


题意:插入最少的字符使得原串成为一个回文串。

思路:dp[i][j]表示原串i到j的子串形成回文串最少需要插入的字符数。然后根据dp[i][j]输出路径。

AC代码如下:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char s[1010];
int dp[1010][1010];
void dfs(int l,int r)
{ if(dp[l][r]>=0)
   return;
  dfs(l+1,r);
  dfs(l,r-1);
  dfs(l+1,r-1);
  dp[l][r]=min(dp[l+1][r]+1,dp[l][r-1]+1);
  if(s[l]==s[r])
   dp[l][r]=min(dp[l][r],dp[l+1][r-1]);
}
void print(int l,int r)
{ if(l==r)
  { printf("%c",s[l]);
    return;
  }
  if(l>r)
   return;
  if(s[l]==s[r])
  { printf("%c",s[l]);
    print(l+1,r-1);
    printf("%c",s[r]);
    return;
  }
  if(dp[l+1][r]<=dp[l][r-1])
  { printf("%c",s[l]);
    print(l+1,r);
    printf("%c",s[l]);
  }
  else
  { printf("%c",s[r]);
    print(l,r-1);
    printf("%c",s[r]);
  }
}
int main()
{ int n,m,i,j,k,len;
  while(~scanf("%s",s+1))
  { len=strlen(s+1);
    memset(dp,-1,sizeof(dp));
    for(i=1;i<=len;i++)
    { dp[i][i]=0;
      dp[i+1][i]=0;
    }
    dfs(1,len);
    printf("%d ",dp[1][len]);
    print(1,len);
    printf("\n");
  }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: