zoukankan      html  css  js  c++  java
  • POJ2406 Power Strings(循环节)

    Power Strings

    Description
    Given two strings a and b we define a*b to be their concatenation.
    For example, if a = "abc" and b = "def" then a*b = "abcdef". If we think of concatenation as multiplication, exponentiation by a non-negative integer is defined in the normal way: a^0 = "" (the empty string) and a^(n+1) = a*(a^n).
    
    Input
    Each test case is a line of input representing s, a string of printable characters. The length of s will be at least 1 and will not exceed 1 million characters. A line containing a period follows the last test case.
    
    Output
    For each s you should print the largest n such that s = a^n for some string a.
    
    Sample Input
    
    abcd
    aaaa
    ababab
    .
    
    Sample Output
    
    1
    4
    3
    
    Hint
    This problem has huge input, use scanf instead of cin to avoid time limit exceed.
    

    假设一个字符串是由K个子串组成的,
    则字符串最后一个字符的NEXT数值一定是K-1个子串的长度,
    (next数组是"前缀"和"后缀"的最长的共有元素的长度,
    那最后一个字符的next数值就是整个字符串中前缀和后缀最长共有元素的值)
    所以只需求出NEXT[N]后N-NEXT[N]就是可能的最小循环节,
    但是如果N-NEXT[N]不能整除N,则一定原字符串无循环.
    定理:
    1.如果len可以被len - next[len]整除,则表明字符串S可以完全由循环节循环组成,循环周期T=len/L。
    2.如果不能,说明还需要再添加几个字母才能补全。
    需要补的个数是循环个数L-len%L=L-(len-L)%L=L-next[len]%L,L=len-next[len]。

    #include <string.h>
    #include <stdio.h>
    #include <math.h>
    #include <algorithm>
    using namespace std;
    const int maxn=1e6;
    int nxt[maxn],l;
    char s[maxn];
    void getnext()
    {
    	int i=0,j=-1;
    	nxt[0]=-1;
    	while(i<l)
    	{
    		if (j==-1||s[i]==s[j])
    		{
    			i++;
    			j++;
    			nxt[i]=j;
    		}
    		else
    		j=nxt[j];
    	}
    }
    int main()
    {
    	int i,j,n;
    	while(~scanf("%s",s)&&s[0]!='.')
    	{
    		l=strlen(s);
    		getnext();
    		int len=l-nxt[l]; 
    		if (l%len==0)
    		printf("%d
    ",l/len);
    		else
    		printf("1
    "); 	
    	}
    
    	return 0;
    }
  • 相关阅读:
    用记事本编写一个Servlet项目
    Servlet开发(一)
    41、java与mysql乱码的问题
    40、JDBC相关概念介绍
    mysql-5.7.12-winx64安装版配置、使用
    39、集合线程安全问题
    38、各Set实现类的性能分析
    电脑取随机数是什么原理,是真正的随机数吗?转自知乎.
    创建Car类,实例化并调用Car类计算运输的原料量是否足够
    用Random类输出验证码
  • 原文地址:https://www.cnblogs.com/shidianshixuan/p/14319327.html
Copyright © 2011-2022 走看看