HDU(1867)A + B for you again (KMP)
#include <iostream> #include <stdio.h> #include <string> #include <string.h> #include <algorithm> #include <math.h> #include <vector> #include <map> #include <queue> #include <stack> #include <stdlib.h> using namespace std; const int maxn = 100002; char s1[maxn],s2[maxn]; int next[maxn]; void getNext(char *s){ int j=0,k=-1; next[0]=-1; int len = strlen(s); while( j < len ){ if(k == -1 || s[j] == s[k]) next[++j] = ++k; else k = next[k]; } } int kmp(char *s,char *pat){ int i = 0,j = 0; int len1 = strlen(s); int len2 = strlen(pat); getNext(pat); while(i < len1 && j < len2){ if( j == -1 || s[i] == pat[j]){ ++i; ++j; } else j = next[j]; } if( i >= len1 ) return j; return 0; } int main(){ while(scanf("%s%s",s1,s2)!=EOF){ int ans1,ans2; ans2 = kmp(s1,s2); ans1 = kmp(s2,s1); if( ans1 == ans2) if(strcmp(s1,s2) < 0) printf("%s%s",s1,s2+ans2); else printf("%s%s",s2,s1+ans1); else if( ans2 > ans1 ) printf("%s%s",s1,s2+ans2); else printf("%s%s",s2,s1+ans1); printf("\n"); } return 0; }