zoukankan      html  css  js  c++  java
  • UVALive 3026(KMP算法)

    UVALive 3026     KMP中next[]数组的应用;

    题意:给出一个字符串,问该字符串每个前缀首字母的位置和该前缀的周期。

    思路:裸KMP直接上就是了;

    设该字符串为str,str字符串的长度为len,next[]的有关前缀的周期的性质

    如果len % (len - next[len]) = 0 (next[len]  != 0)则该字符串有长度为len - next[len] 的循环节(长度最小的重复循环单位),而这个循环节的周期就是len / (len - next[len])。

    上代码

    PS:注意空格.........为什么这个UVA上不是格式错误直接判WA。。。

    #include <iostream>
    #include <cstdio>
    #include <cmath>
    #include <cstring>
    #include <queue>
    #include <vector>
    #include <algorithm>
    #define FRE() freopen("in.txt","r",stdin)
    #define INF 0x3f3f3f3f
    
    using namespace std;
    typedef pair<double,int> P;
    const int maxn = 1e6+10;
    int n,net[maxn];
    char str[maxn];
    
    void GetNext()
    {
        memset(net,0,sizeof(net));
        net[0] = -1;
        int str_len = strlen(str);
        int j = -1,i = 0;
        while(i < str_len)
        {
            if(j == -1 || str[i] == str[j])
            {
                i++;
                j++;
                net[i] = j;
            }
            else
                j = net[j];
        }
        for(int i = 1; i <= n; i++)
        {
            if(i%(i-net[i]) == 0 && i/(i-net[i]) >= 2)
            {
                printf("%d %d
    ",i,i/(i-net[i]));
            }
        }
    }
    
    int main()
    {
        int cnt = 0;
        while(~scanf("%d",&n) && n)
        {
            scanf("%s",str);
            printf("Test case #%d
    ",++cnt);
            GetNext();
            printf("
    ");
        }
        return 0;
    }
    View Code
  • 相关阅读:
    基于阈值的图像分割
    boost_1_45_0安装
    分类后评价精度的几个因子的概念
    数字图像去噪典型算法及matlab实现
    返回数值类型
    C标准库之assert
    区域增长
    OTB Chapter 1
    win7下,如何在odbc数据源中添加access驱动的问题
    c语言文件操作模式大全
  • 原文地址:https://www.cnblogs.com/sykline/p/9737790.html
Copyright © 2011-2022 走看看