zoukankan      html  css  js  c++  java
  • 【POJ2406】 Power Strings (KMP)

    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.
     
     
    【题意】
      一个字符串的最大重复字串。
      即一个字符串是一个子串最多重复多少次得到的。
     
    【分析】
      

      ① len==1||s[next[len-1]]!=s[len-1] ans=1;
      ② len%(len-next[len])==0 ans= len/(len-next[len]);

      原因如图:

      

    代码如下:

     1 #include<cstdio>
     2 #include<cstdlib>
     3 #include<cstring>
     4 #include<iostream>
     5 #include<algorithm>
     6 #include<queue>
     7 using namespace std;
     8 #define Maxn 1000010
     9 
    10 char s[Maxn];
    11 int len,nt[Maxn];
    12 
    13 
    14 void kmp()
    15 {
    16     nt[1]=0;
    17     int p=0;
    18     for(int i=2;i<=len;i++)
    19     {
    20         while(s[i]!=s[p+1]&&p) p=nt[p];
    21         if(s[i]==s[p+1]) p++;
    22         nt[i]=p;
    23     }
    24 }
    25 
    26 int main()
    27 {
    28     int n,i;
    29     while(1)
    30     {
    31         gets(s+1);
    32         len=strlen(s+1);
    33         if(len==1&&s[1]=='.') break;
    34         kmp();
    35         if(len%(len-nt[len])==0) printf("%d
    ",len/(len-nt[len]));
    36         else printf("1
    ");
    37     }
    38 }
    [POJ2406]

    2016-07-20 16:30:02

  • 相关阅读:
    Mysql数据优化--DBA梳理珍藏篇
    Spring缓存注解@Cacheable
    Spring常用知识点
    谈一谈对MySQL InnoDB的认识及数据库事物处理的隔离级别
    MySQL主从复制的实现过程
    List 与 数组 互转
    位运算实现小正整数乘法
    最大的K个数
    Java 编码与字符(2)
    JSP工作原理
  • 原文地址:https://www.cnblogs.com/Konjakmoyu/p/5688814.html
Copyright © 2011-2022 走看看