题目链接:http://acm.split.hdu.edu.cn/showproblem.php?pid=1711
题意:求字符串b在字符串a中第一次出现的位置,没有则输出-1
思路:直接借用kuangbin大神的模板,具体看代码
代码:
#include <cstdio>
#include <cmath>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <numeric>
#include <set>
#include <string>
#include <cctype>
#include <sstream>
#define INF 0x3f3f3f3f
#define INF 0x3f3f3f3f
#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1
using namespace std;
typedef long long LL;
typedef pair<LL, LL> P;
const int maxn = 1e4 + 5;
const int mod = 1e8 + 7;
int Next[maxn];
int a[1000000+5], b[maxn];
int n, m;
void getNext() {
int j, k;
j = 0;
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;
getNext();
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 t;
int main() {
//freopen ("in.txt", "r", stdin);
cin>>t;
while (t--){
cin>>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;
}