hdu1686 KMP裸題

秋招快有着落啦,十一月中去北京區賽膜拜衆神。

哎,好長一段時間沒有刷過,重頭拾起,最近得專題是字符串。

Trie前一排又敲了一遍,KMP今天敲了一下。

題目一大堆廢話,實際就是判斷模式串出現得次數,我是對着算法導論僞代碼敲得,一次AC,真得很水。

/***********************************************************
	> 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];
            //cout<<q<<endl;
        }
    }
    return res;
}
int main()
{
    int C;
    p[0]=T[0]='1';
    while(scanf("%d",&C)!=EOF){
        while(C--){
            scanf("%s",p+1);
            scanf("%s",T+1);
            printf("%d\n",kmp(strlen(T)-1,strlen(p)-1));
        }

    }
}


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