HDU

题意:求w串在T串中的出现次数。(可重叠出现)

#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 = 10000 + 10;
const int MAXT = 1000000 + 10;
using namespace std;
char w[MAXN], t[MAXT];
int Next[MAXN];
int wlen, tlen;
void getNext(){
    Next[0] = 0;
    for(int p = 1, k = 0; p < wlen; ++p){
        while(k > 0 && w[p] != w[k]) k = Next[k - 1];
        if(w[p] == w[k]) ++k;
        Next[p] = k;
    }
}
int kmp(){
    getNext();
    int cnt = 0;
    for(int p = 0, k = 0; p < tlen; ++p){
        while(k > 0 && t[p] != w[k]) k = Next[k - 1];
        if(t[p] == w[k]) ++k;
        if(k == wlen){
            ++cnt;
            k = Next[k - 1];
        }
    }
    return cnt;
}
int main(){
    int T;
    scanf("%d", &T);
    while(T--){
        scanf("%s%s", w, t);
        wlen = strlen(w);
        tlen = strlen(t);
        printf("%d
", kmp());
    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/tyty-Somnuspoppy/p/7488399.html