zoukankan      html  css  js  c++  java
  • poj 2406 Power Strings(KMP入门,next函数理解)

    Power Strings
    Time Limit: 3000MS   Memory Limit: 65536K
    Total Submissions: 37685   Accepted: 15590

    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.

    Source

    基础题目,只要是理解next函数。

     1 #include<iostream>
     2 #include<vector>
     3 #include <cstdio>
     4 #include <cstring>
     5 #include <cstdlib>
     6 #include <math.h>
     7 #include<algorithm>
     8 #define ll long long
     9 #define eps 1e-8
    10 using namespace std;
    11 
    12 int nexts[1050];
    13 char b[1050];
    14 
    15 void pre_nexts(int m)
    16 {
    17     memset(nexts,0,sizeof(nexts));
    18     int j = 0,k = -1;
    19     nexts[0] = -1;
    20     while(j < m)
    21     {
    22         if(k == -1 || b[j] == b[k])  nexts[++j] = ++k;
    23         else k = nexts[k];
    24     }
    25 }
    26 int main(void)
    27 {
    28     while(scanf("%s",b),b[0] != '.')
    29     {
    30         int n = (int)strlen(b);
    31         pre_nexts(n);
    32         if(n % (n-nexts[n]) == 0 && n/(n - nexts[n]) > 1) printf("%d
    ",n/(n-nexts[n]));
    33         //根据next函数的最后一个匹配数,算出循环节点~
    34         else printf("1
    ");
    35     }
    36     return 0;
    37 }
  • 相关阅读:
    面向消息的持久通信与面向流的通信
    通信协议
    [1]序章,基本
    深拷贝和浅拷贝
    堆/栈 内存管理相关
    C++的四种cast(显示类型转换)
    智能指针相关
    C++对象模型:单继承,多继承,虚继承
    HTTP/TCP
    [读书笔记] 为什么绝不在构造/析构函数中调用virtual函数
  • 原文地址:https://www.cnblogs.com/henserlinda/p/4718639.html
Copyright © 2011-2022 走看看