hdu 1867 kmp A + B for you again

来源:互联网 发布:vscode js代码提示 编辑:程序博客网 时间:2024/06/07 19:57

hud-1867- A + B for you again

 


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

题意:寻找两个字符串的前后缀最大相等部分(第一个字符串的前缀第二个字符串的后缀相等,或者第二个字符按串的前缀或者后缀,选取两者中最长输出),输出一个串不相等部分+相等部分+另一个串的不相等部分。当两个字符串完全不相等时间,按长短输出,长度短的在前,长度较长的再后。长度相等但两个字符串完全不等时间,按字典序较小的在前,较大的在后输出。

解题思路:

 水题一道,两次kmp,分别用两个字符串做模板串进行匹配。当出现第一个字符串有后缀和第二的字符串前缀相等时间,匹配的i,j中一定有一个是超出字符串的长度而另一个是小于字符串的长度。不知道一个字符串前缀相等的部分大还是后缀的相等部分大,因此需要两次kmp。

题中题意不明,真假前缀没有指明,数据abcdef  ef,这样的数据没有,无论是输出abcdef还是abcdefef都可以。

但如果是有这样的数据就要知道该如何改变。

代码:

#include<stdio.h>#include<string.h>int next[100010];void get(char s[]){int i=1,j=0,len;len=strlen(s);while(i<len){ if(j==0&&s[i]!=s[j])   {     next[i]=0;i++;   }else if(j>0&&s[i]!=s[j])  {   j=next[j-1];  }else { next[i]=j+1;i++;j++;  } }}int kmp(char s0[],char s1[]){int i,j,k,len0,len1;get(s1);len0=strlen(s0);len1=strlen(s1);i=0;j=0;while(i<len0&&j<len1)//while(i<len0)  判断条件改为这个,可以保证输出是按假前缀输出。而代码中的条件时保证按真前后缀输出{if(j==0&&s0[i]!=s1[j])   i++;else if(j>0&&s0[i]!=s1[j])   j=next[j-1];else   { i++;j++;} }if(i==len0)return j;    return 0;}int main(){char s1[100010];char s2[100010];int x,y;while(scanf("%s%s",s1,s2)!=EOF){x=kmp(s1,s2);y=kmp(s2,s1);        if(x == y)        {              if(strcmp(s1,s2)>0)              {                  printf("%s",s2);                  printf("%s\n",s1+x);              }              else              {                  printf("%s",s1);                  printf("%s\n",s2+x);              }          }          else if(x>y)         {              printf("%s",s1);              printf("%s\n",s2+x);          }          else          {              printf("%s",s2);              printf("%s\n",s1+y);          }  }return 0;}
一道不错的水题,可以帮助加深理解next数组。

原创粉丝点击