标签:style io os ar for strong sp div c
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 abcdcba
0 aaaa
2 abcba
1 baab
0 abababaabababa
9 pqrsabcdpqrqpdcbasrqp
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<limits.h> typedef long long LL; using namespace std; const int maxn=1100; char str[maxn]; int dp[maxn][maxn]; int len; void output(int i,int j) { // cout<<"1111 "<<endl; if(i>j) return ; if(i==j) { printf("%c",str[i]); return ; } if(str[i]==str[j]) { printf("%c",str[i]); output(i+1,j-1); printf("%c",str[i]); } else if(dp[i][j]==dp[i+1][j]+1) { printf("%c",str[i]); output(i+1,j); printf("%c",str[i]); } else { printf("%c",str[j]); output(i,j-1); printf("%c",str[j]); } } int solve() { memset(dp,0,sizeof(dp)); for(int l=2;l<=len;l++) { for(int i=0;i+l-1<len;i++) { int j=i+l-1; dp[i][j]=INT_MAX; if(str[i]==str[j]) dp[i][j]=dp[i+1][j-1]; else dp[i][j]=min(dp[i][j],min(dp[i+1][j]+1,dp[i][j-1]+1)); } } } int main() { while(~scanf("%s",str)) { len=strlen(str); solve(); printf("%d ",dp[0][len-1]); output(0,len-1); puts(""); } return 0; }
标签:style io os ar for strong sp div c
原文地址:http://blog.csdn.net/u013582254/article/details/39852723