hdu 1867

来源:互联网 发布:sql format 日期 编辑:程序博客网 时间:2024/06/05 03:02

A + B for you again

Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6283    Accepted Submission(s): 1553


Problem Description
Generally speaking, there are a lot of problems about strings processing. Now you encounter another such problem. If you get two strings, such as “asdf” and “sdfg”, the result of the addition between them is “asdfg”, for “sdf” is the tail substring of “asdf” and the head substring of the “sdfg” . However, the result comes as “asdfghjk”, when you have to add “asdf” and “ghjk” and guarantee the shortest string first, then the minimum lexicographic second, the same rules for other additions.
 

Input
For each case, there are two strings (the chars selected just form ‘a’ to ‘z’) for you, and each length of theirs won’t exceed 10^5 and won’t be empty.
 

Output
Print the ultimate string by the book.
 

Sample Input
asdf sdfgasdf ghjk
 

Sample Output
asdfgasdfghjk
 


kmp的运用,很考验思维分别对两个字符串求前缀和后缀的相同长度的最大值进行比较,注意一个细节如果一个字符串是另一个字符串的子串需要特判

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 1000010;
char str1[N], str2[N];
int nex[N];
void getnext(char *p);
int kmp(char *p,char *q);
int len;


int main()
{
    while(scanf("%s %s",str1, str2)!=EOF)
    {
        int x=kmp(str1,str2);
        int y=kmp(str2,str1);
        if(x==y)
        {
            if(strcmp(str1,str2)>0)
            {
                printf("%s",str2);
                printf("%s\n",str1+x);
            }
            else
            {
                printf("%s",str1);
                printf("%s\n",str2+x);
            }
        }
        else if(x>y)
        {
             printf("%s",str1);
             printf("%s\n",str2+x);
        }
        else
        {
            printf("%s",str2);
            printf("%s\n",str1+y);
        }
    }
    return 0;
}


int kmp(char *p,char *q)
{
    getnext(q);
    int len1=strlen(p), len2=strlen(q);
    int i=0, j=0;
    while(i<len1&&j<len2)
    {
        if(j==-1||p[i]==q[j])
        {
            i++,j++;
        }
        else
        {
            j=nex[j];
        }


        if(j==len2&&i!=len1)
        {
            j=nex[j];
        }
    }
    if(i==len1)
    {
        return j;
    }
    else
    {
        return 0;
    }
}


void getnext(char *p)
{
    int  k=-1, j=0;
    len=strlen(p);
    nex[0]=-1;
    while(j<len)
    {
        if(k==-1||p[k]==p[j])
        {
            k++,j++;
            if(p[k]!=p[j])
            {
                nex[j]=k;
            }
            else
            {
                nex[j]=nex[k];
            }
        }
        else
        {
            k=nex[k];
        }
    }
    return ;
}

0 0