題意:給你兩個串,求他們串連成的最短串,串連時合并相同部分。還有當以兩種方式串連(s1s2、s2s1)得到的最短長度相同時,取字典序最小那種。
#include<iostream>#include<cstdio>#include<cstring>using namespace std;const int N=100005;int next[N];void init(char *s)//get next[]{ int i,j; next[0]=0; for(i=1,j=0;s[i];i++) { while(j>0&&s[j]!=s[i]) j=next[j-1]; if(s[j]==s[i]) j++; next[i]=j; }}int getLength(char *s1,char *s2)//get the length of the same part{ int i,j; init(s2); for(i=j=0;;i++) { while(j>0&&s1[i]!=s2[j]) j=next[j-1]; if(s1[i]==s2[j]) j++; if(s1[i+1]=='\0') break; if(s2[j]=='\0') j=0; } return j;}void output(char *s1,char *s2,int n){ int len=strlen(s1); for(int i=0;i<len-n;i++) putchar(s1[i]); printf("%s\n",s2);}int main(){ char s1[N],s2[N]; while(~scanf("%s%s",s1,s2)) { int len1=getLength(s1,s2); int len2=getLength(s2,s1); if(len1>len2) output(s1,s2,len1); else if(len2>len1) output(s2,s1,len2); else { if(strcmp(s1,s2)<0) output(s1,s2,len1); else output(s2,s1,len2); } } return 0;}