码迷,mamicode.com
首页 > 其他好文 > 详细

HDU1867 A + B for you again KMP应用

时间:2015-02-23 16:46:39      阅读:148      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!