HDU 1711 Number Sequence——kmp
2017-09-04 20:18
435 查看
模板题
#include <cstdio>
using namespace std;
const int maxn = 1e6 + 10;
int t, n, m, T[maxn], P[maxn], fail[maxn];
void Getfail() {
fail[0] = 0;
for (int i = 1, j = 0; i < m; i++) {
while (j && P[i] != P[j]) j = fail[j - 1];
if (P[i] == P[j]) j++;
fail[i] = j;
}
}
int Search() {
Getfail();
for (int i = 0, j = 0; i < n; i++) {
while (j && T[i] != P[j]) j = fail[j - 1];
if (T[i] == P[j]) j++;
if (j == m) return i - j + 2;
}
return -1;
}
int main() {
scanf("%d", &t);
for (int kase = 1; kase <= t; kase++) {
scanf("%d %d", &n, &m);
for (int i = 0; i < n; i++) scanf("%d", &T[i]);
for (int i = 0; i < m; i++) scanf("%d", &P[i]);
printf("%d\n", Search());
}
return 0;
}
#include <cstdio>
using namespace std;
const int maxn = 1e6 + 10;
int t, n, m, T[maxn], P[maxn], fail[maxn];
void Getfail() {
fail[0] = 0;
for (int i = 1, j = 0; i < m; i++) {
while (j && P[i] != P[j]) j = fail[j - 1];
if (P[i] == P[j]) j++;
fail[i] = j;
}
}
int Search() {
Getfail();
for (int i = 0, j = 0; i < n; i++) {
while (j && T[i] != P[j]) j = fail[j - 1];
if (T[i] == P[j]) j++;
if (j == m) return i - j + 2;
}
return -1;
}
int main() {
scanf("%d", &t);
for (int kase = 1; kase <= t; kase++) {
scanf("%d %d", &n, &m);
for (int i = 0; i < n; i++) scanf("%d", &T[i]);
for (int i = 0; i < m; i++) scanf("%d", &P[i]);
printf("%d\n", Search());
}
return 0;
}
相关文章推荐
- HDU 1711 Number Sequence KMP
- HDU 1711 (裸KMP) Number Sequence
- [HDU](1711)Number Sequence ---KMP(串)
- HDU 1711:Number Sequence(KMP)
- hdu 1711 Number Sequence kmp模式匹配
- hdu 1711 Number Sequence KMP
- hdu 1711 Number Sequence KMP
- hdu 1711 Number Sequence KMP(水)
- HDU 1711 Number Sequence KMP
- HDU - 1711 Number Sequence KMP
- HDU 1711:Number Sequence (KMP入门)
- 【HDU】1711 Number Sequence KMP
- HDU1711 Number Sequence KMP基础
- HDU 1711 Number Sequence kmp
- Hdu 1711 KMP Number Sequence
- HDU 1711 Number Sequence KMP入门
- HDU 1711 Number Sequence KMP题解
- [HDU] 1711 Number Sequence KMP
- hdu 1711: Number Sequence【KMP算法】
- HDU 1711-Number Sequence