首页 > 代码库 > CodeForces - 471D MUH and Cube Walls
CodeForces - 471D MUH and Cube Walls
CodeForces - 471D
记录差分,利用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 }
CodeForces - 471D MUH and Cube Walls
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。