【poj3461】 Oulipo

http://poj.org/problem?id=3461 (题目链接)

题意

  求一个字符串在另一个字符串中出现的次数。

Solution

  KMP裸题,太久没写过了,都忘记怎么求next数组了。。水一发→_→

细节

  next[0]=-1。

代码

// poj3461
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<cmath>
#define LL long long
#define inf 2147483640
#define Pi acos(-1.0)
#define free(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout);
using namespace std;

const int maxn=1000010;
char s[maxn],t[maxn];
int next[maxn];

void calnext() {
	next[0]=-1;
	for (int i=1,j=-1;s[i];i++) {
		while (j!=-1 && s[i]!=s[j+1]) j=next[j];
		if (s[j+1]==s[i]) j++;
		next[i]=j;
	}
}
int main() {
	int T;scanf("%d",&T);
	while (T--) {
		scanf("%s%s",s,t);
		int sum=0;
		calnext();
		for (int i=0,j=-1;t[i];i++) {
			while (j!=-1 && s[j+1]!=t[i]) j=next[j];
			if (s[j+1]==t[i]) j++;
			if (!s[j+1]) sum++,j=next[j];
		}
		printf("%d\n",sum);
	}
	return 0;
}

  

posted @ 2016-11-11 19:30  MashiroSky  阅读(272)  评论(0编辑  收藏  举报