码迷,mamicode.com
首页 > 其他好文 > 详细

HDU - 1711 Number Sequence(kmp)

时间:2017-09-07 10:10:56      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:names   str   pre   cstring   cpp   sequence   string   ext   lib   

题意:求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;
}

  

HDU - 1711 Number Sequence(kmp)

标签:names   str   pre   cstring   cpp   sequence   string   ext   lib   

原文地址:http://www.cnblogs.com/tyty-Somnuspoppy/p/7488030.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!