hdu 1867 A + B for you again

6 篇文章 0 订阅

A + B for you again

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


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

给你两个字符串,求输出两个字符串合并的最小字符串;如果第一个字符串的末尾几个字符和第2个字符串的前面几个字符相同即可输出一遍即可,例如:asdf  df -> asdf  ;asdf  sd->asdfsd; asdf   sdc->asdfsdc;

规则:1.长度越短优先

           2.字典序越小优先

思路:分别以每个串为主串,用另一个串与它进行匹配,返回子串合并到主串后面时的长度,然后取短的,相同长度则取字典序优先的。。

AC代码:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#include <cmath>
#include <string>
#include <algorithm>

using namespace std;

int next[100005];
char s1[100005];
char s2[100005];
void get_next(char s[])
{
    memset(next,0,sizeof(next));
    int len=strlen(s);
    for(int i=1;i<len;i++)
        {
            int temp=next[i-1];
            while(temp&&s[temp]!=s[i])
            temp=next[temp-1];
            if(s[temp]==s[i])
            next[i]=temp+1;
            else
            next[i]=0;
        }
}

int kmp(char a[],char b[])
{
    int len1=strlen(a);
    int len2=strlen(b);
    get_next(b);
    int i,j=0;
    for(i=0;i<len1;i++)
    {
        while(j>0&&a[i]!=b[j])
        j=next[j-1];
        if(a[i]==b[j]) j++;
        else
        j=0;
    }
    return len1+len2-j;
}
int main()
{
    while(scanf("%s%s",s1,s2)!=EOF)
    {
        int len1=strlen(s1);
        int len2=strlen(s2);
        int ans1=kmp(s1,s2);
        int ans2=kmp(s2,s1);
        if(ans1<ans2)
        {
            printf("%s%s\n",s1,s2+(len2-(ans1-len1)));
        }
        else if(ans1>ans2)
        {
            printf("%s%s\n",s2,s1+(len1-(ans2-len2)));
        }
        else
        {
            if(strcmp(s1,s2)<0)
            printf("%s%s\n",s1,s2+(len2-(ans1-len1)));
            else
            printf("%s%s\n",s2,s1+(len1-(ans2-len2)));
        }
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值