您的位置:首页 > 大数据 > 人工智能

HDU 1867 A + B for you again (KMP应用)

2015-02-11 09:19 495 查看

A + B for you again

Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 4636 Accepted Submission(s): 1193

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




Author
Wang Ye


Source
2008杭电集训队选拔赛——热身赛

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1867

题目大意:给两个串,合并它们,如果其中一个的前缀和另一个的后缀相同,则相同部分为它们合并后的公共部分,有多种合并方式先考虑它们的长度,优先得到短的,长度相同时优先得到字典序小的

题目分析:把串s1和串s2分别与对方进行模式匹配,设匹配后得到的匹配长度为l1和l2,若l1==l2则比较字典序,比如如果s1 < s2,则输出s1和s2中与s1非公共的部分及s2 + l2,若l1 < l2输出s2和s1 + l2,s1 +l2就是s1中与s2非公共的部分

#include <cstdio>
#include <cstring>
int const MAX = 1e5 + 5;
int next[MAX];
char s1[MAX], s2[MAX];

void get_next(char *a)
{
    int i = 0, j = -1;
    next[0] = -1;
    while(a[i] != '\0')
    {
        if(j == -1 || a[i] == a[j])
        {
            i++;
            j++;
            if(a[i] == a[j])
                next[i] = next[j];
            else
                next[i] = j;
        }
        else
             j = next[j];
    }
}

int KMP(char *a, char *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)
    {
        int l1 = KMP(s1, s2);
        int l2 = KMP(s2, s1);
        if(l1 == l2)
        {
            if(strcmp(s1, s2) < 0)
                printf("%s%s\n", s1, s2 + l1);
            else
                printf("%s%s\n", s2, s1 + l1);
        }
        else if(l1 < l2)
            printf("%s%s\n", s2, s1 + l2);
        else
            printf("%s%s\n", s1, s2 + l1);
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: