hdu 2087 剪花布条 KMP

剪花布条

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


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

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

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

Sample Input
abcde a3 aaaaaa aa #
 

Sample Output
0 3
 

Author
qianneng
 

Source
 

Recommend
lcy   |   We have carefully selected several similar problems for you:  1711 3746 3336 2091 2094 
基础的KMP,nextval数组和next数组的细节还有点没有搞清楚,还得多捉摸捉摸。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
#include <map>
#include <stack>
#include <vector>
#include <set>
#include <queue>
#pragma comment (linker,"/STACK:102400000,102400000")
#define maxn 1005
#define MAXN 2005
#define mod 1000000009
#define INF 0x3f3f3f3f
#define pi acos(-1.0)
#define eps 1e-6
typedef long long ll;
using namespace std;

char str[maxn],pstr[maxn];
int nextval[maxn];

void get_nextval()
{
    int plen=strlen(pstr+1);
    int i=1,j=0;
    while (i<plen)
    {
        if (j==0||pstr[i]==pstr[j])
        {
            i++;
            j++;
            if (pstr[i]!=pstr[j])
                nextval[i]=j;
            else
                nextval[i]=nextval[j];
        }
        else
            j=nextval[j];
    }
}

int KMP()
{
    int plen=strlen(pstr+1);
    int len=strlen(str+1);
    int i=0,j=0,ans=0;
    while (i<=len)
    {
        if (j==0||str[i]==pstr[j])
        {
            if (j>=plen)
            {
                ans++;
                j=0;
            }
            i++;
            j++;
        }
        else
            j=nextval[j];
    }
    return ans;
}

int main()
{
    while (scanf("%s",str+1))
    {
        if (str[1]=='#')
            break;
        scanf("%s",pstr+1);
        get_nextval();
        printf("%d\n",KMP());
    }
    return 0;
}


posted @ 2014-10-18 17:05  浪子小黄人  阅读(158)  评论(0编辑  收藏  举报