二次联通门 : LibreOJ #103. 子串查找
/* LibreOJ #103. 子串查找 kmp */ #include <cstdlib> #include <cstring> #include <cstdio> #define Max 1000900 int next[Max]; void Get_Next (char *line) { next[0] = -1; for (register int pos_1 = 0, pos_2 = -1, Len = strlen (line); pos_1 < Len; ) if (pos_2 == -1 || line[pos_1] == line[pos_2]) { pos_1 ++; pos_2 ++; next[pos_1] = pos_2; } else pos_2 = next[pos_2]; } int Answer; void Kmp (char *line, char *__txt) { int Len_txt = strlen (__txt); int Len_ = strlen (line); if (Len_txt < Len_) { puts (0); exit (0); } for (register int pos_1 = 0, pos_2 = 0; pos_2 < Len_txt && pos_1 < Len_; ) { if (pos_1 == -1 || line[pos_1] == __txt[pos_2]) { pos_1 ++; pos_2 ++; } else pos_1 = next[pos_1]; if (pos_1 == Len_) { Answer ++; pos_1 = next[pos_1]; } } } char line[Max]; char __txt[Max]; int main (int argc, char *argv[]) { scanf ("%s", __txt); scanf ("%s", line); Get_Next (line); Kmp (line, __txt); printf ("%d", Answer); return 0; }
时间: 2024-11-09 22:55:15