HDU 1867 A + B for you again 【KMP】

来源:互联网 发布:nba本赛季数据 编辑:程序博客网 时间:2024/06/04 19:16

题目链接

题目:

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


WA:题目意思比较隐晦,要判断a+b和b+a的情况如果两个长度相同按字典序输出


AC代码:

#include <iostream>#include <stdio.h>#include <cstring>#define N 100010using namespace std;char a[N],b[N];int nx[N];void getnext(char x[], int m){    nx[0] = 0;    int j = 0;    for(int i = 1; i < m; i++)    {        while(x[i] != x[j] && j)            j = nx[j-1];        if(x[i] == x[j])            j++;        nx[i] = j;    }}int KMP(char x[], char y[], int n, int m){    int j = 0;    for(int i = 0; i < n; i++)    {        while(x[i] != y[j] && j)            j = nx[j-1];        if(x[i] == y[j])            j++;        if(j == m && i != n-1)            j = nx[j-1];    }    return j;}int main(){    while(~scanf(" %s %s", a, b))    {        int n = strlen(a);        int m = strlen(b);        getnext(b,m);        int k = KMP(a,b,n,m);        getnext(a,n);        int kk = KMP(b,a,m,n);        if(k == kk)        {            if(strcmp(a,b) < 0)                printf("%s%s\n",a,b+k);            else                printf("%s%s\n",b,a+k);        }        else if(k > kk)            printf("%s%s\n", a, b+k);        else            printf("%s%s\n", b, a+kk);    }    return 0;}


原创粉丝点击