题目链接:https://cn.vjudge.net/problem/HDU-2594
题意:s2的所有后缀与s1前缀的最长匹配
题解:用ex数组时,注意后缀要全部匹配就完事了
#include <bits/stdc++.h>
using namespace std;
const int N = 500100;
int nex[N], ex[N];
void get_nex(char *s) {
int i = 0, j, pos, len = strlen(s);
nex[0] = len;
while(s[i] == s[i + 1] && i + 1 < len) i++;
nex[1] = i;
pos = 1;
for(i = 2; i < len; i++) {
if(nex[i - pos] + i < nex[pos] + pos)
nex[i] = nex[i - pos];
else {
j = nex[pos] + pos - i;
if(j < 0) j = 0;
while(i + j < len && s[j] == s[j + i]) j++;
nex[i] = j;
pos = i;
}
}
}
void ex_kmp(char *s, char *t) {
int i = 0, j, pos, l1 = strlen(s), l2 = strlen(t);
get_nex(s);
while(s[i] == t[i] && i < l1 && i < l2) i++;
ex[0] = i;
pos = 0;
for(int i = 1; i < l2; i++) {
if(nex[i - pos] + i < ex[pos] + pos)
ex[i] = nex[i - pos];
else {
j = ex[pos] + pos - i;
if(j < 0) j = 0;
while(i + j < l2 && j < l1 && s[j] == t[i + j]) j++;
ex[i] = j;
pos = i;
}
}
}
int main() {
char s[N], t[N];
int pos, cnt, len;
while(~scanf("%s %s", s, t)) {
ex_kmp(s, t);
cnt = 0;
len = strlen(t);
for(int i = 0; i < len; i++) {
if(ex[i] + i == len && ex[i] > cnt) {
cnt = ex[i];
pos = i;
}
}
if(cnt == 0) printf("0\n");
else {
for(int i = pos; i < pos + cnt; i++) printf("%c", t[i]);
printf(" %d\n", cnt);
}
}
return 0;
}