2012-02-22 08:33:08Morris

[UVA] 11475 - Extend to Palindrome

Problem E

Extend to Palindromes

Time Limit : 3 seconds

 

 

 

Your task is, given an integer N, to make a palidrome (word that reads the same when you reverse it) of length at least N. Any palindrome will do. Easy, isn't it? That's what you thought before you passed it on to your inexperienced team-mate. When the contest is almost over, you find out that that problem still isn't solved. The problem with the code is that the strings generated are often not palindromic. There's not enough time to start again from scratch or to debug his messy code. Seeing that the situation is desperate, you decide to simply write some additional code that takes the output and adds just enough extra characters to it to make it a palindrome and hope for the best. Your solution should take as its input a string and produce the smallest palindrome that can be formed by adding zero or more characters at its end.

 

 

 

Input

 

 

 

 

Input will consist of several lines ending in EOF. Each line will contain a non-empty string made up of upper case and lower case English letters ('A'-'Z' and 'a'-'z'). The length of the string will be less than or equal to 100,000.

 

 

 

 

 

 

 

Output

 

 

 

For each line of input, output will consist of exactly one line. It should contain the palindrome formed by adding the fewest number of extra letters to the end of the corresponding input string.

 

 

 

 

 

 

 

Sample Input

Sample Output

 

 

 

 

 

aaaa
abba
amanaplanacanal
xyz

aaaa
abba
amanaplanacanalpanama
xyzyx








做法 : KMP

做出另外一個反轉字串的字串, 與原先的字串做KMP匹配

#include<stdio.h>
#include<string.h>
#define MaxL 100005
char A[MaxL], B[MaxL];
int P[MaxL];
void KMPTable(char *A) {
    int i, j;
    P[0] = -1, i = 1, j = -1;
    while(A[i]) {
        while(j >= 0 && A[j+1] != A[i])
            j = P[j];
        if(A[j+1] == A[i])
            j++;
        P[i++] = j;
    }
}
int KMPMatching(char A[], char B[]) {
    KMPTable(B);
    int i, j, Alen, Blen;
    Alen = strlen(A), Blen = strlen(B);
    for(i = 0, j = -1; i < Alen; i++) {
        while(j >= 0 && B[j+1] != A[i])
            j = P[j];
        if(B[j+1] == A[i])    j++;
/*        if(j == Blen-1)
            return true;
*/
    }
    return j;
}
void Solve(char A[]) {
   
    int Alen = strlen(A), Blen = Alen;
    int i, j;
    for(i = 0, j = Blen-1; i < Alen; i++, j--)
        B[j] = A[i];
    B[Blen] = '\0';
    int tail = KMPMatching(A, B);
    for(i = Blen-1; i > tail; i--)
        printf("%c", B[i]);
    printf("%s\n", B);
}
int main() {
    while(scanf("%s", A) == 1)
        Solve(A);
    return 0;
}