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

A + B for you again

时间:2017-11-07 01:25:20      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:mat   code   scan   sam   another   content   book   tee   about   

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.

InputFor 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.OutputPrint the ultimate string by the book.Sample Input
asdf sdfg
asdf ghjk
Sample Output
asdfg
asdfghjk

合并字符串
很奇怪,一开始提交总是不对,以为写错了,换c++提交就对了
代码:

#include <stdio.h>
#include <string.h>
char a[100005],b[100005];
int next[100005];
void getnext(int n,char *s)
{
    int i = 0,k = -1;
    next[i] = -1;
    while(i < n)
    {
        if(k == -1 || s[k] == s[i])
        {
            next[++ i] = ++k;
        }
        else k = next[k];
    }
}
int kmp(char *p,char *q)
{
    int n = strlen(p),m = strlen(q);
    getnext(m,q);
    int i = -1,k = -1;
    while(i < n)
    {
        if(k == -1 || p[i] == q[k])
        {
            i ++;
            k ++;
        }
        else k = next[k];
    }
    return k;
}
int main()
{
    while(~scanf("%s%s",a,b))
    {
        int d = kmp(a,b),e = kmp(b,a);//保存a后缀和b前缀的最大重叠 以及 反过来 比较哪个大 就重叠那个 按相应顺序输出,如果相等就按字典序
        if(d > e)printf("%s%s",a,b+d);
        else if(d < e)printf("%s%s",b,a+e);
        else
        {
            if(strcmp(a,b) > 0)printf("%s%s",b,a+e);
            else printf("%s%s",a,b+d);
        }
        putchar(\n);
    }
}

 

A + B for you again

标签:mat   code   scan   sam   another   content   book   tee   about   

原文地址:http://www.cnblogs.com/8023spz/p/7795862.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!