zoukankan      html  css  js  c++  java
  • poj2406 Power Strings 模式匹配算法KMP变形

    http://poj.org/problem?id=2406

    题意:字符串A分解为数个相同的字符串B,求B的最多的个数,如ababab,可由3个ab组成,abcabab由1个abcabab组成(即本身),

    aaaa由4个a组成。

    解题:本题并不要用到KMP的整个算法,而只是用到了KMP算法中的:next[i]的值。所于要对next[i]比较理解。

    以str="abcaababc"为例:

     

    i

    0

    1

    2

    3

    4

    5

    6

    7

    8

    a

    b

    c

    a

    a

    b

    a

    b

    c

    next[i]

    -1

    0

    0

    0

    1

    1

    2

    1

    2

    最后结果为ans=next[n]/(n-next[n])+1;n为字符串长度,如上面的"abcaababc",next[n]为next[9]=0,即next[]值我们要多算一位。

    Source Code

    Problem: 2406   User: 541780774
    Memory: 5592K   Time: 157MS
    Language: G++   Result: Accepted


    Source Code

    #include <stdio.h>
    #include <stdlib.h>
    #include<string.h>
    #include<iostream>
    using namespace std;
    char str[1000000];
    int next[1000000],n;
    void get_next()//求模式串的“next[]”值
    {
         long i=0,j=-1;
         next[0]=-1;
         while(i<=n)
         {
           if(j==-1||str[i]==str[j])
             next[++i]=++j;
           else j=next[j];
         }
    }

    main()
    {
       long i,ans;
       while(gets(str))
       {
          if(strcmp(str,".")==0) break;
          n=strlen(str);
          get_next();
          for(i=n;i>=0;i--)
            if(next[i]!=next[i-1]+1||next[i]==1)
              break;
          if(next[n]%(n-next[n])==0)
             ans=next[n]/(n-next[n])+1;
          else
            ans=1;
          printf("%ld\n",ans);
       }
         
          system("pause");
    }

  • 相关阅读:
    除法
    01.python对象
    00.基础入门
    00.斐波那契数列第n项
    16.分治排序
    15.快速排序
    14.插入排序--希尔排序(缩小增量排序)
    13.插入排序--直接插入排序(简单插入排序)
    12.选择排序
    11.冒泡排序
  • 原文地址:https://www.cnblogs.com/zxj015/p/2740279.html
Copyright © 2011-2022 走看看