hdu 1867 A + B for you again

来源:互联网 发布:java 接口参数泛型 编辑:程序博客网 时间:2024/06/05 06:50

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 sdfgasdf ghjk

Sample Output
asdfgasdfghjk

给你两个字符串,求输出两个字符串合并的最小字符串;如果第一个字符串的末尾几个字符和第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;}