POJ Oulipo(KMP模板题)

题意:找出模板在文本串中出现的次数

思路:KMP模板题

#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<string>
#include<map>
#include<set>
#include<ctime>
#define eps 1e-6
#define LL long long
#define pii (pair<int, int>)
//#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;

const int maxt = 1000000 + 100;
const int maxp = 10000 + 100;
//const int INF = 0x3f3f3f3f;

char P[maxp], T[maxt];
int f[maxp];

void getFail() {
	int m = strlen(P);
	f[0] = 0; f[1] = 0;
	for(int i = 1; i < m; i++) {
		int j = f[i];
		while(j && P[i]!=P[j]) j = f[j];
		f[i+1] = P[i]==P[j] ?

j+1 : 0; } } int find_p() { int ans = 0; int n = strlen(T), m = strlen(P); getFail(); int j = 0; for(int i = 0; i < n; i++) { while(j && P[j]!=T[i]) j = f[j]; if(P[j] == T[i]) j++; if(j == m) ans++, j=f[j]; } return ans; } int main() { //freopen("input.txt", "r", stdin); int t; cin >> t; while(t--) { scanf("%s%s", P, T); int ans = find_p(); cout << ans << endl; } return 0; }


原文地址:https://www.cnblogs.com/jzssuanfa/p/6999538.html