题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1711
题目大意:最基础的字符串匹配,只不过这里用整数数组代替了字符串。
给你两个数组?\(a[1..N]\)?和?\(b[1..M]\)?,找到最小的 \(K\) 使得?\(a[K] = b[1], a[K + 1] = b[2], ...... , a[K + M - 1] = b[M]\) 。
题目分析:就是最基础的KMP字符串匹配,改一下数据类型。
实现代码如下:
#include <cstdio>
#include <string>
using namespace std;
const int maxn = 1001000;
int T, n, m, nxt[maxn], cas = 1;
int s[maxn], t[maxn];
void cal_next() {
for (int i = 0, j = -1; i < m; i ++) {
while (j != -1 && t[j+1] != t[i]) j = nxt[j];
nxt[i] = (j+1 < i && t[j+1] == t[i]) ? ++j : -1;
}
}
int find_first_s_has_t_position() {
cal_next();
for (int i = 0, j = -1; i < n; i ++) {
while (j != -1 && t[j+1] != s[i]) j = nxt[j];
if (t[j+1] == s[i]) {
j ++;
if (j >= m-1) {
return i - j + 1;
}
}
}
return -1;
}
int main() {
scanf("%d", &T);
while (T--) {
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i ++) scanf("%d", s+i);
for (int i = 0; i < m; i ++) scanf("%d", t+i);
int pos = find_first_s_has_t_position();
printf("%d\n", pos);
}
return 0;
}
作者:zifeiy
HDU1711 Number Sequence 题解 KMP算法
原文:https://www.cnblogs.com/codedecision/p/11794409.html