HDOJ_1711_KMP 求匹配位置
2014-05-07 20:17
337 查看
HDOJ_1711_KMP 入门
/* HDOJ_1711_KMP 求匹配位置 * * I really like this KMP in door * * Author : a_clay 2014/05/06 */ #include <iostream> #include <cstdio> #include <string> #include <cstring> #include <vector> #include <algorithm> #include <cmath> #define Bug cout << "here\n"; using namespace std; const int N = 1000005; const int M = 10005; int s ; int t[M]; int next[M]; void get_next(int len) { int i, j; i = 0; j = -1; next[0] = -1; while (i < len - 1) { if (j == -1 || t[i] == t[j]) { i++; j++; next[i] = j; } else { j = next[j]; // 核心中的核心,KMP中的KMP。 } } } int kmp(int sl, int tl) { int i, j; i = 0; j = 0; while (i < sl && j < tl) { if (j == -1 || s[i] == t[j]) { //j == -1 是第一个就没有匹配上,类似于传统方法,i要向后移动,因为-1的巧妙设置,所以j依然很好的移动,i 还是从第一位 开始从 j==0比较 i++; j++; } else { j = next[j];} } if (j == tl) { return i-j+1; } else return -1; } // abcabcababcabcabdef // abcabcabd int main() { int T, n, m, ans; cin >> T; while (T--) { cin >> n >> m; int i; for (i = 0; i < n; i++) { scanf("%d", s+i); } for (i = 0; i < m; i++) { scanf("%d", t+i); } get_next(m); ans = kmp(n, m); cout << ans << endl; } return 0; }
相关文章推荐
- HDOJ_1711_KMP 求匹配位置
- KMP / hdu 1711 [找到匹配的位置并返回]
- KMP / hdu 1711 [找到匹配的位置并返回]
- 【KMP求字符串第一个匹配位置】hdu 1711
- hdu 1711 Number Sequence -- (KMP 求数列第一匹配的位置)
- HDU 1711 Number Sequence【KMP】【模板题】【水题】(返回匹配到的第一个字母的位置)
- HDU 1711 KMP求匹配位置
- KMP / hdu 1711 [找到匹配的位置并返回]
- 匹配串HDOJ 1711 Number Sequence(KMP)
- hdoj 1711 Number Sequence 【KMP】
- hdoj 1711 Number Sequence【求字串在母串中第一次出现的位置】
- hdu1711——Number Sequence(KMP求位置)
- hdoj1711-- Number Sequence(KMP模板)
- hdoj 1711 Number Sequence【kmp(数字数组)】
- HDOJ---1711 Number Sequence[KMP模版]
- hdoj 2087 剪花布条 (简单的KMP匹配)
- hdoj 1711 Number Sequence 【KMP 入门--晕晕滴】
- hdoj 1686Oulipo (简单KMP匹配)
- hdoj 1711 Number Sequence 【KMP】
- HDU 1711 Number Sequence (KMP找子串第一次出现的位置)