KMP以及next数组应用--POJ1961

本文详细解析了KMP算法在处理百万级字符串匹配问题中的应用,通过使用next数组来解决字符串重复匹配的问题,同时提供了代码实现和解析过程。

题目地址:点击打开链接http://poj.org/problem?id=1961

百万级字符串..无从下手,T到死哭

从网上查到要用KMP。。我之前也是看过的,欺负我读书少么,KMP与这个题有神马联系。


题目分析:该题用到了next数组,next数组代表的是"前缀"和"后缀"的最长的共有元素的长度(必然小于本身长度),为何用到它可能有些难以理解,慢慢来~

从结果逆推,若一个字符串(len=N)由某个子串(len=x)重复K次得到,则它的next数组值必然为(k-1)*x,这样就得到了K = N / (N - next[N]);

事实上,如果某一个字符串(len=N)的next数组值为x,并且有N整除(N-x),令L=N-x,由前缀后缀的对应关系,即可递推得:


S[(K-1)L+1...KL] = ... =  S[2L+1...3L] = S[L+1...2L] = S[1...L]

 

#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
char a[1000005];
int next[1000005];//从0开始 
void makeNext(const char P[],int next[])
{
    int q,k;
    int m = strlen(P);
    next[0] = 0;
    for (q = 1,k = 0; q < m; ++q)
    {
        while(k > 0 && P[q] != P[k])
            k = next[k-1];
        if (P[q] == P[k])
        {
            k++;
        }
        next[q] = k;
    }
}

int kmp(const char T[],const char P[],int next[])
{
    int n,m;
    int i,q;
    n = strlen(T);
    m = strlen(P);
    makeNext(P,next);
    for (i = 0,q = 0; i < n; ++i)
    {
        while(q > 0 && P[q] != T[i])
            q = next[q-1];
        if (P[q] == T[i])
        {
            q++;
        }
        if (q == m)
        {
            printf("Pattern occurs with shift:%d\n",(i-m+1));
        }
    }    
}

int main()
{
    int n;
    for(int ii=1;;ii++)
    {
    	cin>>n;
    	if(n==0)
    	{
    		break;
    	}
    	else{
    		cin>>a;
    		cout<<"Test case #"<<ii<<endl;
    		makeNext(a,next);
    		for(int i=2;i<=n;i++)
    		{
    			if(i%(i-next[i-1])==0&&i/(i-next[i-1])>1)
    			{
    				cout<<i<<" "<<i/(i-next[i-1])<<endl;
    			}
    		}
    		cout<<endl;
    	}
    }
    return 0;
}

P.S. KMP是直接找的板,next数组是从0开始定义的。

参考: http://www.cppblog.com/menjitianya/archive/2014/06/20/207354.html

http://www.cnblogs.com/c-cloud/p/3224788.html    


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值