http://acm.hdu.edu.cn/showproblem.php?pid=1867 改天再写细节。 #include<iostream> using namespace std; const int P=500010; int fail[P]; char a[500010],b[500010]; char ans[2][1000010]; int kmp(char* str, char* pat,int w){ int i, j, k; memset(fail, -1, sizeof(fail)); for (i = 1; pat[i]; ++i) { for (k=fail[i-1]; k>=0 && pat[i]!=pat[k+1]; k=fail[k]); if (pat[k + 1] == pat[i]) fail[i] = k + 1; } i = j = 0; while( pat[j] ) { // By Fandywang if( pat[j] == str[i] ) ++i, ++j; else if(j == 0)++i;//第一个字符匹配失败,从str下个字符开始 else j = fail[j-1]+1; if(str[i]==0) { sprintf(ans[w],"%s",str); strcat(ans[w],pat+j); return i-j; } if(pat[j]==0) j=0; } if( !pat[j] ) { sprintf(ans[w],"%s",str); strcat(ans[w],pat+j); return i-j; } } int main() { while (scanf("%s%s",a,b)!=EOF) { kmp(a,b,0); kmp(b,a,1); int len1=strlen(ans[0]); int len2=strlen(ans[1]); if(len1==len2) strcmp(ans[0],ans[1])>0?printf("%s/n",ans[1]):printf("%s/n",ans[0]); else len2>len1?printf("%s/n",ans[0]):printf("%s/n",ans[1]); } }