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

70 篇文章 0 订阅


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);
    }
}

 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值