A + B for you again(HDU-1867)(最长公共前缀和后缀)

A + B for you again

Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7891    Accepted Submission(s): 1984

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

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

题目大意:
给出两个字符串合并出一个长度与字典序最小的字符串,且给出的两个串分别为这个合并字符串的前缀与后缀。

题目分析:

注意是先按照长度最小,然后再按照字典序最小输出。

注意题目要求的是最短的字符串能包含所给的两个字符串,这里的包含一定是前一部分或后一部分包含,不能中间包含。

代码:

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <string>
#include <queue>
#include <vector>
#include <map>
using namespace std;
typedef long long LL;
const int N=100000+999;
int nex[N];
char s1[N],s2[N];
void make_next(int n,char *a)
{
    int i,j;
    nex[0]=0;
    for(i=1,j=0; i<n ; i++)
    {
        while(j>0&&a[i]!=a[j])
            j=nex[j-1];
        if(a[i]==a[j])
            j++;
        nex[i]=j;
    }
}
int KMP(int n,int m,char *a,char *b)
{
    make_next(m,b);
    int i,j;
    for(i=0,j=0; i<n; i++)
    {
        while(j>0&&a[i]!=b[j])
            j=nex[j-1];
        if(a[i]==b[j])
            j++;
        if(j==m)
            break;
    }
    if((i==n-1&&j==m)||i==n) //只能是模式串匹配到主串结束
        return j;
    return 0;
}
int main()
{
    while(scanf(" %s %s",s1,s2)!=EOF)
    {
        int len1=strlen(s1);
        int len2=strlen(s2);
        int b=KMP(len1,len2,s1,s2);
        int a=KMP(len2,len1,s2,s1);
        if(b>a) //s2的前缀与s1的后缀匹配较长
        {
            printf("%s%s\n",s1,s2+b);
        }
        else if(a>b)//s1的前缀与s2的后缀匹配较长
        {
            printf("%s%s\n",s2,s1+a);
        }
        else //如果匹配长度相等则看字典序从小到大
        {
            if(strcmp(s1,s2)<0) printf("%s%s\n",s1,s2+b);
            else printf("%s%s\n",s2,s1+a);
        }
    }
    return 0;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值