HDU - 1711 Number Sequence(kmp)
题意:求b串在a串中第一次出现的位置。
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<iostream>
#include<sstream>
#include<iterator>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<deque>
#include<queue>
#include<list>
#define lowbit(x) (x & (-x))
const double eps = 1e-8;
inline int dcmp(double a, double b){
if(fabs(a - b) < eps) return 0;
return a > b ? 1 : -1;
}
typedef long long LL;
typedef unsigned long long ULL;
const int INT_INF = 0x3f3f3f3f;
const int INT_M_INF = 0x7f7f7f7f;
const LL LL_INF = 0x3f3f3f3f3f3f3f3f;
const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f;
const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};
const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};
const int MOD = 1e9 + 7;
const double pi = acos(-1.0);
const int MAXN = 1000000 + 10;
const int MAXT = 10000 + 10;
using namespace std;
int a[MAXN], b[MAXT], Next[MAXT];
int N, M;
void getNext(){
Next[0] = 0;
for(int p = 1, k = 0; p < M; ++p){
while(k > 0 && b[p] != b[k]) k = Next[k - 1];
if(b[p] == b[k]) ++k;
Next[p] = k;
}
}
int kmp(){
getNext();
for(int p = 0, k = 0; p < N; ++p){
while(k > 0 && a[p] != b[k]) k = Next[k - 1];
if(a[p] == b[k]) ++k;
if(k == M) return p - M + 2;
}
return -1;
}
int main(){
int T;
scanf("%d", &T);
while(T--){
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());
}
return 0;
}

浙公网安备 33010602011771号