码迷,mamicode.com
首页 > 其他好文 > 详细

UVa 10298 - Power Strings

时间:2014-08-21 22:48:45      阅读:343      评论:0      收藏:0      [点我收藏+]

标签:os   io   ar   amp   算法   sp   ios   c   

题目:求一个串的最大的循环次数。

分析:dp,KMP,字符串。这里利用KMP算法。

            KMP的next函数是跳跃到最近的串的递归结构位置(串元素取值0 ~ len-1);

            由KMP过程可知:

            如果存在循环节,则S[0 ~ next[len]-1] 与 S[len-next[len] ~ len-1]相匹配;

            则S[next[len] ~ len-1]就是循环节(且最小),否则next[len]为0;

            因此,最大循环次数为len/(len-next[len]),最小循环节为S[next[len] ~ len-1]。

说明:强大的KMP(⊙_⊙)。

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>

using namespace std;

char str[1000004];
int  next[1000004];

void getnext( char *T, int L )  
{  
    next[0] = -1;  
    int i = 0,j = -1;  
    while ( i < L ) {  
        if ( j == -1 || T[i] == T[j] ) {  
            i ++; j ++;  
            next[i] = j;  
        }else j = next[j];  
    }  
}  

int main()
{
	while ( scanf("%s",str) && strcmp( str, "." ) ) {
		int len = strlen(str); 
	  	getnext( str, len );
	  	printf("%d\n",len/(len-next[len]));
	}
	return 0;
}

UVa 10298 - Power Strings,布布扣,bubuko.com

UVa 10298 - Power Strings

标签:os   io   ar   amp   算法   sp   ios   c   

原文地址:http://blog.csdn.net/mobius_strip/article/details/38738157

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!