Thursday, 26 July 2012

UVa 11475 - Extend to Palindrome Solution

#include<iostream>
#include<list>
#include<string>
#include<cstring>
#include<sstream>
#include<cctype>
#include<string.h>
#include<algorithm>
#include<cmath>
#include<stack>
#include<fstream>
#include<cstdlib>
#include<vector>
#include<map>
#include<set>
#include<utility>
#include<iomanip>
#include<queue>

using namespace std;

#define INF (1<<29)
#define SET(a) memset(a,-1,sizeof(a))
#define ALL(a) a.begin(),a.end()
#define CLR(a) memset(a,0,sizeof(a))
#define FILL(a,v) memset(a,v,sizeof(a))
#define PB push_back
#define FOR(i,n) for(int i = 0;i<n;i++)
#define PI acos(-1.0)
#define EPS 1e-9
#define MP(a,b) make_pair(a,b)
#define min3(a,b,c) min(a,min(b,c))
#define max3(a,b,c) max(a,max(b,c))
#define READ(f) freopen(f, "r", stdin)
#define WRITE(f) freopen(f, "w", stdout)
#define LL long long
#define MX 1000010
#define MOD 1000000007

char text[MX],pattern[MX];
int failur[MX],length,cnt;

void FailureFunction()
{
    int i=1,j=0;
    failur[0]=0;
    while(i<length)
    {
        if(pattern[i]==pattern[j])
        {
            j++;
            failur[i]=j;
            i++;
        }
        else if(j>0)
            j=failur[j-1];
        else
        {
            failur[i]=0;
            i++;
        }
    }
}

void KMPmatch()
{
    FailureFunction();
    int i=0,j=0;

    while(i<length)
    {
        if(text[i]==pattern[j])
        {
            i++;
            j++;
            //if(j>cnt)           //maximum palindrom
                cnt=j;
        }
        else if(j>0)
            j=failur[j-1];
        else
            i++;

    }
}

int main()
{
    while(cin>>text)
    {
        int i,j;
        CLR(failur);
        length=strlen(text);
        for(i=0,j=length-1;j>=0;i++,j--)    //pattern is the revese string of text
        pattern[i]=text[j];

        cnt=0;
        KMPmatch();

        cout<<text;
        for(i=cnt;i<length;i++)             //extra character needed
            cout<<pattern[i];
        cout<<endl;
    }
return 0;
}

No comments:

Post a Comment