zoukankan      html  css  js  c++  java
  • kmp-最小子串回文次数

    poj 2406

    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数组,因为 next 数组所表示的意义就是当前位置前面的串的最长公共前后缀,所以最后一位中的 next 所存的值就表示其前面的前缀的最长公共部分 是多少 ,用总的长度减去前缀的长度 ,就得出了最小回文的串的长度。

    代码示例 :
    /*
     * Author:  ry 
     * Created Time:  2017/10/5 7:29:46
     * File Name: 1.cpp
     */
    #include <iostream>
    #include <cstdio>
    #include <cstdlib>
    #include <cstring>
    #include <cmath>
    #include <algorithm>
    #include <string>
    #include <vector>
    #include <stack>
    #include <queue>
    #include <set>
    #include <time.h>
    #include <map>
    using namespace std;
    const int eps = 1e6+5;
    #define ll long long
    
    char s[eps];
    int next[eps];
    int len;
    
    void getnext(){
        int i = 0, j = -1;
        next[0] = -1;
        while (i != len){
            if (j == -1 || s[i] == s[j]){
                i++;
                j++;
                next[i] = j;
            }
            else j = next[j];
        }
    }
    
    int main() {
        
        while (gets(s) != NULL){
            if (s[0] == '.') break;
            len = strlen(s);
            getnext();   
            int ff = len - next[len];
            if ((len - ff) % ff == 0) printf("%d
    ", len/ff);
            else printf("1
    ");
        }
        
        return 0;
    }
    
    /*
    sadjkghrfkjashioawruiofhasjklryqwodhasnkbfgakjsrhoqwuiyeaskjbtrjksa   
    */
    
    东北日出西边雨 道是无情却有情
  • 相关阅读:
    [Exception] 当前 TransactionScope 已完成
    C# Lazy<T>(转)
    C# 基础概念之延迟加载
    .Net语言中关于AOP 的实现详解
    DataReader、Table、DataSet和Entity相互转化
    ASP.NET Core 2.0 : 五.服务是如何加载并运行的, Kestrel、配置与环境(转)
    ASP.NET Core 2.0 : 四. _Layout与_ViewStart(转)
    ASP.NET Core 2.0 : 三. 项目结构(转)
    ASP.NET Core 2.0 : 二. 开发环境(转)
    ASP.NET Core 2.0 : 一. 概述(转)
  • 原文地址:https://www.cnblogs.com/ccut-ry/p/7628723.html
Copyright © 2011-2022 走看看