BuringStraw

BuringStraw

Oulipo Yizhong OJ P5018

义冢 OJ P5018 Oulipo#

Description#

Given two strings W and T, find the number of occurrences of W as a substring in T.

Input#

The first line is the number of test cases.

Each test case consists of two lines, W and T, representing the pattern string and the original string, respectively.

Output#

For each test case, output the number of matches on a separate line.

Sample Input 1#

3
BAPC
BAPC
AZA
AZAZAZA
VERDI
AVERDXIVYERDIAN

Sample Output 1#

1
3
0

Note#

1 ≤ |W| ≤ 10,000 (here |W| denotes the length of the string W). |W| ≤ |T| ≤ 1,000,000.

Solution#

KMP template problem

I can only write some templates and write a blog post to pass the time...

Code#

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;

const int MAXN=1e6+5;

int nxt[MAXN]={0};

void setNext(string s);
int kmp(string s1,string s2);

int n;

int main()
{
	cin>>n;
	string s1,s2;
	for(int i=1;i<=n;++i)
	{
		cin>>s1>>s2;
		setNext(s1);
		cout<<kmp(s2,s1)<<endl;
	}
	
	return 0;
}
void setNext(string s)
{
	memset(nxt,0,sizeof(nxt));
	nxt[0]=-1;
	int sl=s.size();
	for(int i=1;i<sl;++i)
	{
		int t=nxt[i-1];
		while(s[t+1]!=s[i]&&t>=0)
		{
			t=nxt[t];
		}
		if(s[t+1]==s[i])
		{
			nxt[i]=t+1;
		}
		else
		{
			nxt[i]=-1;
		}
	}
}
int kmp(string s1,string s2)
{
	int i=0,j=0;
	int sl1=s1.size(),sl2=s2.size();
	int cnt=0;
	while(i<sl1)
	{
		if(s1[i]==s2[j])
		{
			++i;
			++j;
			if(j==sl2)
			{
				++cnt;
				j=nxt[j-1]+1;
			}
		}
		else
		{
			if(j==0)++i;
			else j=nxt[j-1]+1;
		}
	}
	return cnt;
}
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.