From a4d53eb1375030f88c5a86eb5c20654e880b251c Mon Sep 17 00:00:00 2001 From: TooYoungTooSimp <6648049+TooYoungTooSimp@users.noreply.github.com> Date: Thu, 12 Jan 2017 20:13:21 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=87=E5=88=86=E6=84=9F=E8=B0=A2@ice1000?= =?UTF-8?q?=EF=BC=8C%%%?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Algorithms/String/KMP.cpp | 98 ++++++++------------------------------- 1 file changed, 19 insertions(+), 79 deletions(-) diff --git a/Algorithms/String/KMP.cpp b/Algorithms/String/KMP.cpp index 01f1589..50f5bfe 100644 --- a/Algorithms/String/KMP.cpp +++ b/Algorithms/String/KMP.cpp @@ -1,91 +1,31 @@ -/*#include +#include #include -char s[100000], p[100000]; -int next[100000]; -void getNext(char* P) -{ - int lenP = strlen(P); - next[0] = -1; - int k = -1, i = 0; - while (i < lenP - 1) - if (k == -1 || P[k] == P[i]) - i++, k++, next[i] = (p[i] == p[k]) ? next[k] : k; - else k = next[k]; -} -int match(char* S, char* P) -{ - int lenS = strlen(S), lenP = strlen(P), i = 0, j = 0; - while (i < lenS && j < lenP) - if (j == -1 || S[i] == P[j]) - i++, j++; - else - j = next[j]; - return j == lenP ? i - j : -1; -} +char a[1 << 20 | 1], b[1 << 14 | 1]; +int la, lb; +int next[1 << 14 | 1]; int main() { + next[0] = -1; int n; scanf("%d", &n); - for (int i = 0; i < n; i++) + while (n--) { - scanf("%s%s", p, s); - getNext(p); - char* str = s; - int pos = match(str, p), ans = 0; - while (pos != -1) + scanf("%s%s", b, a); + la = strlen(a), lb = strlen(b); + for (int i = 1, j = -1; i < lb; i++) { - ans++; - str += pos + 1; - pos = match(str, p); + while (~j && b[j + 1] != b[i]) j = next[j]; + if (b[j + 1] == b[i]) j++; + next[i] = j; + } + int ans = 0; + for (int i = 0, j = -1; i < la; i++) + { + while (~j && b[j + 1] != a[i]) j = next[j]; + if (b[j + 1] == a[i]) j++; + if (j == lb - 1) ans++, j = next[j]; } printf("%d\n", ans); } return 0; -}*/ -#include -#include -using namespace std; -const int mt = 1e6 + 5; -char x[mt], y[mt], next[mt]; -int m, n; -void pre() -{ - int i = 0, j = next[0] = -1; - while (i != m) - { - if (-1 == j || y[i] == y[j]) - next[++i] = ++j; - else - j = next[j]; - } -} -int cnt() -{ - pre(); - int i = 0, j = 0, ans = 0; - while (i != n && j != m) - { - if (-1 == j || y[i] == x[j]) - i++, j++; - else - j = next[j]; - if (j == m) - ans++, i -= j - 1, j = -1; - } - return ans; -} -int main() -{ - int t; - scanf("%d", &t); - while (t--) - { - scanf("%s", x); - scanf("%s", y); - m = strlen(x), n = strlen(y); - //cout<