记录差分,利用kmp对分别除去了第一个数的两个数组进行匹配
注意特判模式串长度为一的情况
1 #include <cstdio> 2 #include <cstring> 3 using namespace std; 4 5 const int maxn = 2e5 + 10; 6 int ans, n, m; 7 8 void find_substring(int pattern[], int text[]) { 9 vector<int> next(n + 1, 0); 10 for (int i = 1; i < n; i++) { 11 int j = i; 12 while (j > 0) { 13 j = next[j]; 14 if (pattern[j] == pattern[i]) { 15 next[i + 1] = j + 1; 16 break; 17 } 18 } 19 } 20 for (int i = 0, j = 0; i < m; i++) { 21 if (j < n && text[i] == pattern[j]) { 22 j++; 23 } else { 24 while (j > 0) { 25 j = next[j]; 26 if (text[i] == pattern[j]) { 27 j++; 28 break; 29 } 30 } 31 } 32 if (j == n) ans++; 33 } 34 } 35 36 int main(int argc, const char * argv[]) { 37 int text[maxn], pattern[maxn]; 38 scanf("%d%d", &m, &n); 39 for (int i = 0; i < m; i++) scanf("%d", &text[i]); 40 for (int i = 0; i < n; i++) scanf("%d", &pattern[i]); 41 for (int i = m - 1; i >= 1; i--) text[i] = text[i] - text[i - 1]; 42 for (int i = n - 1; i >= 1; i--) pattern[i] = pattern[i] - pattern[i - 1]; 43 --n; --m; 44 find_substring(pattern + 1, text + 1); 45 if (n == 0) ans++; 46 printf("%d\n", ans); 47 return 0; 48 }
时间: 2024-10-12 12:33:56