[HDU - 2087] 剪花布條(KMP)

Link:點擊打開鏈接


剪花布條

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 21623    Accepted Submission(s): 13491


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

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

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

Sample Input
abcde a3 aaaaaa aa #
 

Sample Output
0 3


Code:
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<queue>
#include<stack>
using namespace std;
char s1[1010],s2[1010];
int t[1010];  //神奇的是數組名改成next交上去直接CompileError
int KMP()
{
	int i=0,j=0,c=0;
	int a=strlen(s1);
	int b=strlen(s2);
	while(i<a)
	{
		if(j==-1||s1[i]==s2[j])
		{
			++i,++j;
			if(j==b)
			{
				j=0;
				c++;
			}
		}
		else
			j=t[j];
	}
	return c;
}
void getnext(char *s2,int m)
{
	int i=0,j=0;
	t[0]=-1;
	j=t[i];
	while(i<m)
	{
		if(j==-1||s2[i]==s2[j])
			t[++i]=++j;
		else
			j=t[j];
	}
}
int main()
{
	while(~scanf("%s",s1)&&s1[0]!='#')
	{
		scanf("%s",s2);
		int a=strlen(s1);
		int b=strlen(s2);
		getnext(s2,b);
		printf("%d\n",KMP());
	}
return 0;
} 


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