hdu2087(kmp裸題)

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

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

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

Sample Input
abcde a3 aaaaaa aa #
 

Sample Output
0 3
 
用kmp,但是構造next時候,再匹配成功時,不要用q=next[q],而是q=i+1.這個非常容易理解。
和昨天的1686非常相似。
/***********************************************************
	> OS     : Linux 3.13.0-24-generic (Mint-17)
	> Author : yaolong
	> Mail   : [email protected]
	> Time   : 2014年09月24日 星期三 15時31分51秒
 **********************************************************/
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
using namespace std;
int next[12345];
char p[12345];
char T[1234567];
void build_next ( int m )
{
    next[1] = 0;
    int k = 0;
    for ( int q = 2; q <= m; q++ )
    {
        while ( k > 0 && p[k + 1] != p[q] )
        {
            k = next[k];
        }
        if ( p[k + 1] == p[q] )
        {
            k = k + 1;
        }
        next[q] = k;
    }
}
int kmp ( int n, int m )
{
    build_next ( m );
    int q = 0;
    int res = 0;
    for ( int i = 1; i <= n; i++ )
    {
        while ( q > 0 && p[q + 1] != T[i] )
        {
            q = next[q];
        }
        if ( p[q + 1] == T[i] )
        {
            q = q + 1;
        }
        if ( q == m )
        {
            //cout << "Here" << i-m<<"q";
            ++res;
            //q = next[q];
            q=i+1;
            //cout<<q<<endl;
        }
    }
    return res;
}
int main()
{
    int C;
    p[0] = T[0] = '1';
    while ( scanf ( "%s", T + 1 ) != EOF )
    {
        if ( T[1] == '#' )
        {
            break;
        }
        scanf ( "%s", p + 1 );
        printf ( "%d\n", kmp ( strlen ( T ) - 1, strlen ( p ) - 1 ) );
    }
    return 0;
}



發佈了123 篇原創文章 · 獲贊 10 · 訪問量 21萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章