1. 程式人生 > >HDU 2087 減花布條(KMP 匹配)

HDU 2087 減花布條(KMP 匹配)

題目:

Description

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

Input

輸入中含有一些資料,分別是成對出現的花布條和小飾條,其布條都是用可見ASCII字元表示的,可見的ASCII字元有多少個,布條的花紋也有多少種花樣。花紋條和小飾條不會超過1000個字元長。如果遇見#字元,則不再進行工作。 

Output

輸出能從花紋布中剪出的最多小飾條個數,如果一塊都沒有,那就老老實實輸出0,每個結果之間應換行。 

Sample Input

abcde a3
aaaaaa  aa
#

Sample Output

0
3

程式碼:

#include<iostream>
#include<string.h>
using namespace std;

char listn[1005];		//長串
char listm[1005];		//短串
int next_[1005];

void getnext(char *t, int m, int *next)		//m是短串t的長度
{
	int i = 1, j = 0;
	next[1] = 0;
	while (i < m)
	{
		if (j == 0 || t[i] == t[j])
		{
			i++;
			j++;
			if (t[i] != t[j])
next[i] = j; else next[i] = next[j]; } else j = next[j]; } } int main() { ios_base::sync_with_stdio(false); //減小輸入輸出的時間 int n, m; int sum; while (1) { cin >> listn; n = strlen(listn); if (n == 1 && listn[0] == '#')break; cin >> listm; m = strlen(listm); int
i = 0, j = 0; sum = 0; getnext(listm, m, next_); while (i < n) { if (listn[i] == listm[j]) { i++; j++; if (j >= m) { sum++; j = 0; } } else { if (next_[j])j = next_[j]; else { i++; j = 0; } } } cout << sum << endl; } return 0; }