HDU 1711 Number Sequence(kmp)

/* Author: ACb0y Date: 2010年12月31日21:47:36 Type: KMP ProblemID: HDU 1711 Number Sequence Result: 3367520 2010-12-27 21:46:16 Accepted 1711 515MS 4220K 854 B C++ ACb0y */ #include <iostream> using namespace std; int a[1000005]; int b[10005]; int next[10005]; int n, m; void get_next() { int j = 0; int k = -1; next[0] = -1; while (j < m) { if (k == -1 || b[j] == b[k]) { next[++j] = ++k; } else { k = next[k]; } } } int kmp_index() { int i = 0, j = 0; get_next(); while (i < n && j < m) { if (j == -1 || a[i] == b[j]) { ++i; ++j; } else { j = next[j]; } } if (j == m) { return i - m + 1; } else { return -1; } } int main() { #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); #endif int cas; scanf("%d", &cas); while (cas--) { scanf("%d%d", &n, &m); for (int i = 0; i < n; ++i) { scanf("%d", &a[i]); } for (int i = 0; i < m; ++i) { scanf("%d", &b[i]); } printf("%d/n", kmp_index()); } return 0; }

你可能感兴趣的:(c,2010)