`
he91_com
  • 浏览: 375658 次
文章分类
社区版块
存档分类
最新评论

poj 2406 Power Strings kmp算法

 
阅读更多

此题用KMP算法做是最简单的,代码也很短。

#include<stdio.h>
#include<string.h>
char ch[1000005];
int f[1000005];
int main()
{
	int i,j,k;
	while(scanf("%s",ch)!=-1&&ch[0]!='.')
	{
		int m=strlen(ch);
		for(i=1;i<m;i++)
		{
			j=f[i];
			while(j&&ch[i]!=ch[j])j=f[j];
			f[i+1]=ch[i]==ch[j]?j+1:0;
		}
		int tmp=m-1-(f[m]-1);//必须用f[m]-1不能直接f[m-1]
		if(m%tmp==0)
		  printf("%d\n",m/tmp);
        else
          printf("1\n");
	}
	return 0;
}
另外附上滔神的代码,快速读入,优化到32ms

#include<stdio.h>
#include<string.h>

int next[1111111] ;

void get_next ( char *s , int n )
{
	int i , j ;
	j = -1 ;
	next[0] = -1 ;
	for ( i = 1 ; i < n ; i ++ )
	{
		while ( j > -1 && s[j+1] != s[i] ) j = next[j] ;
		if ( s[j+1] == s[i] ) j ++ ;
		next[i] = j ;
	}
}

char s[1111111] ;
int main ()
{
	int n , k ;
	n = 0 ;
	while ( s[n++] = getchar () )
	{
		while ( ( s[n++] = getchar () ) != 10 ) ;
		n -- ;
		if ( n == 1 && s[0] == '.' ) break ;
		get_next ( s , n ) ;
		k = next[n-1] ;
		if ( n % ( n - 1 - k ) ) puts ( "1" ) ;
		else printf ( "%d\n" , n / ( n - 1 - k ) ) ;
		n = 0 ;
	}
}



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics