HDU 2087【kmp模板】

**

剪花布条

**

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

Problem Description

一块花布条,里面有些图案,另有一块直接可用的小饰条,里面也有一些图案。对于给定的花布条和小饰条,计算一下能从花布条中尽可能剪出几块小饰条来呢?

Input

输入中含有一些数据,分别是成对出现的花布条和小饰条,其布条都是用可见ASCII字符表示的,可见的ASCII字符有多少个,布条的花纹也有多少种花样。花纹条和小饰条不会超过1000个字符长。如果遇见#字符,则不再进行工作。

Output

输出能从花纹布中剪出的最多小饰条个数,如果一块都没有,那就老老实实输出0,每个结果之间应换行。

Sample Input

abcde a3
aaaaaa aa

Sample Output

0
3

#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <cmath>
#include <algorithm>

char s1[1010];
char s2[1010];
int next[1010];
void get_next(char *s){
	int len = 0;
	int i = 1;
	next[0] = 0;
	int n = strlen(s);
	while(i < n){
		if(s[i] == s[len]){
			len++;
			next[i] = len;
			i++;
		}
		else{
			if(len > 0){
				len = next[len - 1];
			}else {
				next[i] = 0;
				i++;
			}
			
		} 
	}
}
void  movenext(char *s){
	for(int i = strlen(s) - 1; i >=0; i--) next[i] = next[i - 1];
	next[0] = -1;
}
int kmp(char *s1, char *s2){
	int n = strlen(s2);
	int m = strlen(s1);
	int i = 0;
	int j = 0;
	int ans = 0;
	while(i < m && j < n){
		if(j == -1 || s1[i] == s2[j]){
			i++;
			j++;
		}else {
			j = next[j];
		}
		if(j == n){
			ans++;
			j = 0;
		}
	}
	return ans ;
}
int main(){
	while(scanf("%s", s1) != EOF){
		if(strcmp(s1, "#") == 0) break;
		scanf("%s", s2);
		get_next(s2);
		movenext(s2);
		printf("%d\n",kmp(s1,s2));
	}
	return 0;
}

发布了28 篇原创文章 · 获赞 22 · 访问量 1028

猜你喜欢

转载自blog.csdn.net/qq_45432665/article/details/103285135