poj2406-Power Strings

第一个KMP的题目,感觉蛮好的,虽然以前也敲过,但是当时不是很理解为什么要这样用,后来知道它的原理后,但是一直没有做过相应的题目,虽然这只是一个基础题,但是这也意味着一个好的开始
上面这个是伪造的KMP,下面那个是KMP的典型模板
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>

using namespace std;
const int maxn = 1000010 ;
char str[ maxn ];
int next[ maxn ];
int getnext()
{
	int i , j , len ;
	i = 0 ;
	j = -1 ;
	next[ 0 ] = -1;
	len = strlen( str ) ;
	while( str[ i ] )
	{
		if( j == -1 || str[ i ] == str[ j ] )
		{
			i++;
			j++;
			next[ i ] = j;
		}
		else
			j = next[ j ];
	}
	i = len - j ;
	if( len % i == 0 )
		return len / i ;
	else
		return 1;
}

int main()
{
	while( gets(str)&&str[ 0 ] != '.' )
		cout<< getnext() << endl ;
	return 0 ;
}



kmp中get_next函数使用
// File Name: poj2406.cpp
// Author: bo_jwolf
// Created Time: 2013年04月30日 星期二 19:54:46

#include<vector>
#include<list>
#include<map>
#include<set>
#include<deque>
#include<stack>
#include<bitset>
#include<algorithm>
#include<functional>
#include<numeric>
#include<utility>
#include<sstream>
#include<iostream>
#include<iomanip>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<ctime>

using namespace std;
const int maxn = 1000000 ;
char str[ maxn ];
int next[ maxn ];
int len ;
void get_next()
{
	next[ 0 ] = -1 ;
	int j = 0 , k = -1 ;
	while( j < len )
	{
		if( k == -1 || str[ j ] == str[ k ] )
		{
			j++ ;
			k++ ;
			next[ j ] = k ;
		}
		else
			k = next[ k ] ;
	}
}

int main()
{
	while( scanf( "%s" ,&str ) != EOF )
	{
		if( strcmp( str , "." ) == 0 )
			break;
		len = strlen( str ) ;
		get_next();
		if( len % ( len - next[ len ] ) == 0 && len / ( len - next[ len ] ) > 1 )
			printf( "%d\n" , len / ( len - next[ len ] ) );
		else
			printf( "1\n" ) ;
	}
return 0;
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值