hdu1867——A + B for you again

Keywords: Programming

kmp should be used.
I've been fooling around for a long time. No, it's four months. Today, I inadvertently turn to this question or I won't do it. I copied the following question.
Firstly, the matching of kmp is slightly deformed, using kmp(a,b) and then not the position of output matching, nor the number of output matching, but the input when i==sl, that is, when the original string matches, then pat matches to that position, input j, so that a and B are matched to the other as pattern strings, to see whose prefix can be connected to the length of another suffix. Longer, if the same, then compare the dictionary order

Code:

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
const int N=200050;
int Next[N];
char a[N];
char b[N];
char t[N];
void getNext(char* s){
    memset(Next,0,sizeof(Next));
    int i=0;
    int j=-1;
    Next[0]=-1;
    int l=strlen(s);
    while(i<l){
        if(j==-1 || s[i]==s[j]){
            Next[++i]=++j;
        }
        else{
            j=Next[j];
        }
    }
}
int kmp(char *str,char *pat){
    memset(Next,0,sizeof(Next));
    getNext(pat);
    int i=0,j=0;
    int sl=strlen(str);
    int pl=strlen(pat);
    while(i<sl && j<pl){
        if(j==-1 || str[i]==pat[j]){
            i++;
            j++;
        }
        else{
            j=Next[j];
        }
    }
    if(i==sl){
        return j;
    }
    else{
        return -1;
    }
}
int main(void){
    while(~scanf("%s %s",a,b)){
        int t1=kmp(a,b);
        int t2=kmp(b,a);
        if(t1>t2){
            printf("%s",a);
            printf("%s\n",&b[t1]);
        }
        else if(t1<t2){
            printf("%s",b);
            printf("%s\n",&a[t2]);
        }
        else{
            if(strcmp(a,b)<0){
                printf("%s%s\n",a,&b[t1]);
            }
            else{
                printf("%s%s\n",b,&a[t2]);
            }
        }
    }
    return 0;
}

Posted by jcbarr on Tue, 22 Jan 2019 19:33:13 -0800