UVA-11475 Extend to Palindrome(KMP)

That Italy: multiple sets of input, output and configured to a string (can only be inserted at the end) which minimizes the palindromic sequence

Idea: If the string is inserted into the case can have any of dp LCS (the longest common subsequence process) manner. We put a string s, s1 is set to the inverse of the longest common subsequence found by dp, and then subtracting the original length is the longest common subsequence length of the completion (the case when inserted)

But this question is added at the end it should be a continuous substring matching, so we use the KMP algorithm to match the longest string of consecutive sub-section, this is not the same part of the proceeds completion.

 

Complete code:

#include<cstdio>
#include<cstring>
#include <string>
#include <iostream>
#include <cmath>
#include<algorithm>
using namespace std;
const int maxn = 1000;
int nex[maxn];
int len1,len2;
string a,b;
void getnext(){
    int i= 0,j =-1;//i为副串的序号 
    nex[i] = j;
    while(i<len2){
        if(j==-1||b[i]==b[j]){
            nex[++i] =++j;
        }else j = nex[j];
    }
}
int kmp(){

    int ans = 0;
    int cnt = 0;
    int count = 0;
    int i= 0,j=0;
    getnext();
    for(i=0;i<len1;i++)
    {
        while(j>0&&a[i]!=b[j]){
            j=nex[j];
            cnt = 0;
        }
        if(a[i]==b[j])    {
            j++; cnt++;
            count = max(cnt,count);
        }
    }
    return count;
}

int main()
{
    int lena,lenb,i,j;
    while(cin>>a)
    {
        b.assign(a);
        reverse(b.begin(),b.end()); 
        len1 = a.size();
        len2 = b.size();
        int ans = kmp();
        if(ans==len1) cout<<a<<endl; 
        else{
            string s = b.substr(ans,len1);
            cout<<a<<s<<endl;
        }
    }
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/Tianwell/p/11234108.html