【HDOJ】1867 A + B for you again

时间:2022-05-19 15:54:32

KMP算法的应用。

 #include <stdio.h>
#include <string.h> #define MAXNUM 100005 char src[MAXNUM], des[MAXNUM];
char src1[MAXNUM*], des1[MAXNUM*];
int next[MAXNUM]; void getnext(char *p, int *next, int len) {
int j, k;
j = ;
k = -;
next[] = -;
while (j+ < len) {
if (k==- || p[j]==p[k]) {
++j;
++k;
if (p[j] == p[k])
next[j] = next[k];
else
next[j] = k;
} else {
k = next[k];
}
}
} int kmp(char *src, char *des, int lens, int lend) {
int i, j; i = j = ;
memset(next, , sizeof(next));
getnext(des, next, lend);
while (i < lens) {
while (src[i] != des[j]) {
if (next[j] == -) {
j = ;
break;
}
j = next[j];
}
if (src[i] == des[j])
++j;
++i;
} return j;
} int main() {
int i, j, k;
char *p, *q;
int lens, lend; while (scanf("%s %s", src, des) != EOF) {
lens = strlen(src);
lend = strlen(des);
j = kmp(src, des, lens, lend);
k = kmp(des, src, lend, lens);
if (j == k) {
strcpy(src1, src);
for (i=j; i<lend; ++i)
src1[lens++] = des[i];
src1[lens] = '\0';
strcpy(des1, des);
for (i=k; i<lens; ++i)
des1[lend++] = src[i];
des1[lend] = '\0';
if (strcmp(src1, des1) < ) {
printf("%s\n", src1);
} else {
printf("%s\n", des1);
}
continue;
} else if (j > k) {
p = src;
q = des;
} else {
p = des;
q = src;
j = k;
}
printf("%s", p);
printf("%s\n", q+j);
} return ;
}