http://acm.hdu.edu.cn/showproblem.php?pid=1867
代码写复杂了~
#include <iostream> #include <cstring> #include <cstdio> using namespace std; char s[100005]; char t[100005]; int nextt[100005]; int nexts[100005]; char res1[200005]; char res2[200005]; void get_next(int *next,char *t) { int l=strlen(t); int i=0; next[0]=-1; int j=-1; while(i<l) { if(j==-1||t[i]==t[j]) { i++; j++; next[i]=j; } else j=next[j]; } } void kmp1(char *s,char *t,int *next,char *res) { int i=0; int j=0; int l1=strlen(s); int l2=strlen(t); if(l1>l2) i=l1-l2; while(i<l1&&j<l2) { if(j==-1||s[i]==t[j]) { i++; j++; } else j=next[j]; } strcpy(res,s); //puts(res); strcpy(res+l1,t+j); //puts(res); } int main() { while(scanf("%s%s",s,t)!=EOF) { get_next(nextt,t); get_next(nexts,s); kmp1(s,t,nextt,res1); kmp1(t,s,nexts,res2); int l1=strlen(res1); int l2=strlen(res2); //puts() if(l1<l2) puts(res1); else if(l1>l2) puts(res2); else { if(strcmp(res1,res2)<0) puts(res1); else puts(res2); } } return 0; }