首页 > 其他 > 详细

HDU1867 A + B for you again KMP应用

时间:2015-02-23 16:43:57      阅读:225      评论:0      收藏:0      [点我收藏+]

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 sdfg
asdf ghjk

Sample Output

asdfg
asdfghjk

解题思路

对两个字符串分别KMP,得到相同前后缀长度。再根据长度判断该如何输出

#include <cstdio>
#include <cstring>
const int maxn = 100010;
int next[maxn];
char s1[maxn],s2[maxn];
int len1,len2;
void get_next(char *a)
{
    int len = strlen(a);
    int k = -1;
    int j = 0;
    next[j] = k;
    while(a[j] != ‘\0‘) {
        if(k == -1 || a[j] == a[k]) {
            k++;j++;
            next[j] = k;
        }else k = next[k];
    }
}
int kmp(char *a,char *b)
{ //a主串 b模式串
    get_next(b);
    int i = 0,j = 0;
    while(a[i] != ‘\0‘) {
        if(j == -1 || a[i] == b[j]) {
            i++;j++;
        }else j = next[j];
    }
    return j;
}
int main()
{
    while(scanf("%s%s",s1,s2) != EOF) {
        len1 = strlen(s1);
        len2 = strlen(s2);
        int str1 = kmp(s1,s2);
        int str2 = kmp(s2,s1);
        if(str1 == str2) {
            if(strcmp(s1,s2) < 0) printf("%s%s\n",s1,s2+str1);
            else printf("%s%s\n",s2,s1+str1);
        }else if(str1 < str2) {
            printf("%s%s\n",s2,s1+str2);
        }else printf("%s%s\n",s1,s2+str1);
    }
    return 0;
}

HDU1867 A + B for you again KMP应用

原文:http://blog.csdn.net/area_52/article/details/43916547

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!