HDU 2087 剪花布條(KMP 出現次數 不可重疊)

題目鏈接

題意:一塊花布條,裏面有些圖案,另有一塊直接可用的小飾條,裏面也有一些圖案。對於給定的花布條和小飾條,計算一下能從花布條中儘可能剪出幾塊小飾條來呢?

分析:輸出模式串在匹配串中出現的次數,不可重疊。

#include <iostream>
#include <cmath>
#include <iomanip>
#include <cstring>
#include <vector>
#include <string>
#include <map>
#include <queue>
#include <stack>
#include <set>
#include <cstdio>
#include <algorithm>
#define INF 0x3f3f3f3f
#define PI acos(-1)
using namespace std;
typedef long long ll;
typedef pair<string, string> P;
const int mod=1e9+7;
const int maxn=1e6+10;


int nx[maxn];

void getnx(string x){
	int m=x.size();
	int i,j;
	j=nx[0]=-1;
	i=0;
	while (i<m){
		if (j==-1 || x[i]==x[j]){
			i++,j++;
			if (x[i]==x[j])
				nx[i]=nx[j];
			else nx[i]=j;
		}
		else j=nx[j];
	}
}

int kmp_count(string s, string t){
	int n=s.size();
	int m=t.size();
	int i=0,j=0,ans=0;
	getnx(t);
	while (i<n){
		while (-1!=j && s[i]!=t[j]) j=nx[j];
		i++;
		j++;
		if (j>=m){
			ans++;
			j=0; 
		}
	}
	return ans;
}

int s[maxn],t[maxn];
int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	string s,t;
	while (cin>>s){
		if (s[0]=='#') break;
		cin>>t;
		cout<<kmp_count(s,t)<<endl;
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章