POJ - 3461 Oulipo(kmp)
题意:求模式串t在主串s中的出现次数。
#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 t[MAXN], s[MAXT]; int _next[MAXN]; int slen, tlen; void getNext(){ int j = 0, k = -1; _next[0] = -1; while(j < tlen){ if(k == -1 || t[j] == t[k]) _next[++j] = ++k; else k = _next[k]; } } int kmp_count(){ if(slen == 1 && tlen == 1){ return s[0] == t[0] ? 1 : 0; } getNext(); int ans = 0, j = 0; for(int i = 0; i < slen; ++i){ while(j > 0 && s[i] != t[j]) j = _next[j]; if(s[i] == t[j]) ++j; if(j == tlen){ ++ans; j = _next[j]; } } return ans; } int main(){ int T; scanf("%d", &T); while(T--){ memset(_next, 0, sizeof _next); scanf("%s%s", t, s); tlen = strlen(t); slen = strlen(s); printf("%d\n", kmp_count()); } return 0; }