pku 2406 && pku 1961 Period && hdu3746 Cyclic Nacklace

嘿嘿,以前写的,刚刚突然看到的,就贴一下咯,KMP 的求next[]数组的活用,求最长重复字串

 pku2406

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 char str [1000010];
int next[1000010];
 
int getnext()
{
 int i= 0, j= -1; next[0]= -1;
 
while( str[i] )//这个过程其实就是在求next[]数组
 {
 if( j== -1 || str[i]== str[j] )
 {
 ++i,++j;
 next[i]= j;
 }
 else j= next[j];
 }
int len= strlen(str);
 i= len- j;
if( len% i== 0 ) return len/ i;
 else return 1;
}
 int main()
{
 while( gets( str), str[0]!= '.' )
 printf("%d\n", getnext() );
 
return 0;
}

 pku 1961

#include<iostream>
#include<string.h>
using namespace std;
char str[1000010];
int net[1000010],len;
void get_next()
{
	net[0]=-1;
	int i=0,j=-1;
	while(str[i])
	{
		if(j==-1 || str[i]==str[j])
		{
			i++;j++;
			net[i]=j;
		}
		else j=net[j];
	}
}
int main()
{
	int cas=0;
	while(scanf("%d",&len)==1 && len)
	{
		scanf("%s",str);
		printf("Test case #%d\n",++cas);
		get_next();
		for(int i=2;i<=len;i++)
		{
	    	int k=i-net[i];
		    if(i%k==0 && i/k >=2)
		    	printf("%d %d\n",i,i/k);
		}
		puts("");
	}
	return 0;
}

 hdu 3746 Cyclic Nacklace

View Code
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 100000+10;
char p[N];
int nxt[N],m;
void get_next()
{
    nxt[0]=-1;
    int k=-1;
    for(int i=1;i<=m-1;i++)
    {
        while(k>-1 && p[k+1] !=p[i])
            k=nxt[k];
        if(p[k+1]==p[i])
            ++k;
        nxt[i]=k;
    }
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%s",p);
        m=strlen(p);
        get_next();
        int len=m-nxt[m-1]-1;
        if(len!=m && m%len==0)
            printf("0\n");
        else printf("%d\n",len-m%len);
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/nanke/archive/2011/11/07/2238676.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值