1. 程式人生 > >kmp統計最多出現幾個模式串

kmp統計最多出現幾個模式串

剪花布條

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


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

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

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

Sample Inputabcde a3 aaaaaa aa #
Sample Output0 3
#include <bits/stdc++.h>

using namespace std;
int n, m;
char ptr[1000000+100];  //模式串
char str[1000000+100];  //主串
int nextt[1000000+100];

void kmp_pre()
{
    int j, k;
    j = 0; k = -1; nextt[0] = -1;
    int nt = 0;
    while(j < m) {
        if(k==-1 || ptr[j] == ptr[k]) {
            ++j;
            nextt[j] = ++k;
        }
        else
            k = nextt[k];
    }
}

int kmp()
{
    int i=0, j=0;
    int ans = 0;
    kmp_pre();
    while(i < n && j<m) {
        if(j == -1 || str[i] == ptr[j])
        {
            i++; j++;
        }
        else
            j = nextt[j];
        if(j == m) {  //每當統計到一個模式串,更新答案
            j = 0;
            ans++;
        }
    }
    return ans;
}

int main()
{
    int t, x;
    while(scanf("%s", str) ) {
        if(str[0]=='#') break;
        scanf("%s", ptr);
        m = strlen(ptr);


        n = strlen(str);

        int ans = kmp();
        printf("%d\n", ans);
    }
    return 0;
}