zoukankan      html  css  js  c++  java
  • POJ 2406 Power Strings

    Time Limit: 3000MS   Memory Limit: 65536K
    Total Submissions: 44595   Accepted: 18629

    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

    题目大意: 给定一个字符串,问最多是多少个相同子串不重叠连接构成。

    解题思路:
    KMP的next数组应用。这里主要是如何判断是否有这样的子串,和子串的个数。

          若为abababa,显然除其本身外,没有子串满足条件。而分析其next数组,next[7] = 5,next[5] = 3,next[3] = 1,

          即str[2..7]可由ba子串连接构成,那怎么否定这样的情况呢?很简单,若该子串满足条件,

          则len%sublen必为0。sunlen可由上面的分析得到为len-next[len]。

                因为子串是首尾相接,len/sublen即为substr的个数。

                若L%(L-next[L])==0,n = L/(L-next[L]),else n = 1

          对KMP不太熟悉的可以看这里:从头到尾理解KMP算法

     

    AC代码:

     1 #include <stdio.h>
     2 #include <string.h>
     3 char str[1000010];
     4 int next[1000010];
     5 void getnext()  //获取next数组
     6 {
     7     int i = 0,j = -1;
     8     next[0] = -1;
     9     int len = strlen(str);
    10     while (i < len)
    11     {
    12         if (j == -1 || str[i] == str[j])
    13         {
    14             i ++;
    15             j ++;
    16             next[i] = j;
    17         }
    18         else
    19             j = next[j];
    20     }
    21 }
    22 int main()
    23 {
    24    while (~scanf("%s",str))
    25    {
    26        if (strcmp(str,".")==0)  //如果str数组为“.”则结束
    27             break;
    28        int len = strlen(str);
    29        getnext();
    30        if (len%(len-next[len])==0)
    31             printf("%d
    ",len/(len-next[len]));
    32        else
    33             printf("1
    ");
    34    }
    35    return 0;
    36 }
    View Code
     
  • 相关阅读:
    IBM ThinkPad SL400 XP驱动
    IMAIL系统修改IP地址的处理方法
    微信小程序setData的回调方法
    数据库的事务常识
    Java中的多线程
    微信小程序合并两个json对象
    微信小程序setData修改对象的属性或者数组中的某个对象的属性
    索引常识
    并发与并行的区别
    避免问题发生的代码规范
  • 原文地址:https://www.cnblogs.com/yoke/p/5858930.html
Copyright © 2011-2022 走看看