zoukankan      html  css  js  c++  java
  • ACM训练二C题

    kmp对我真无奈,我对kmp真苦恼。就是个算法嘛,我以为凭我脖子上的东西可以搞定,现在好了--搞得我头都大了。要我写个啥next的值,五个字:那都不是事。一到啥实际应用吧,我意识不行了,搞不清next到底有什么作用,能干什么。就好比见到了二分啊--

    此题的意思呢,我弄了很久,其实是找相同串,比如ACMACMACMACMACMA,从后往前看next就行了,比如最后一个next[15] = 13,代表前13个字符串和后13位相同,直接用总长16 - 13 = 3,为一个解,接下来看next[13]了,一直这样找出结果,输出时一定注意格式,我交了4次全错在这里。

    For each prefix with length P of a given string S,if

    S[i]=S[i+P] for i in [0..SIZE(S)-p-1],

    then the prefix is a “period” of S. We want to all the periodic prefixs.

    Input

    Input contains multiple cases.

    The first line contains an integer T representing the number of cases. Then following T cases.

    Each test case contains a string S (1 <= SIZE(S) <= 1000000),represents the title.S consists of lowercase ,uppercase letter.

    Output

    For each test case, first output one line containing "Case #x: y", where x is the case number (starting from 1) and y is the number of periodic prefixs.Then output the lengths of the periodic prefixs in ascending order.

    Sample Input

    4
    ooo
    acmacmacmacmacma
    fzufzufzuf
    stostootssto
    

    Sample Output

    Case #1: 3
    1 2 3
    Case #2: 6
    3 6 9 12 15 16
    Case #3: 4
    3 6 9 10
    Case #4: 2
    9 12

    #include <iostream>
    #include<cstring>
    using namespace std;
    
    int a[1000100],next[1000100];
    int m;
    char s[1000100];
    void getNext()
    {
        int j;
        next[0] = 0; next[1] = 0;
        for(int i = 1;i < m;i++)
        {
            j = next[i];
            while(j && s[i]!=s[j])
            {
                j = next[j];
            }
    
            next[i+1] = s[i] == s[j]?j+1:0;
    
        }
    }
    
    int main()
    {
        int n,count,where = 1;
        cin >> n;
        while(n--)
        {
    
            cin >> s;
            m = strlen(s);
                   // cout<< m;
            count = 0;
            int t = m;
            getNext();
    
            while(next[m])
            {
                a[count++] = t - next[m];
                m = next[m];
            }
    
    
    
            cout << "Case #" << where <<": " << count+1 << endl;
    
            where++;
            for(int i = 0;i < count ;i++)
            {
    
                cout << a[i] << " ";
            }
            cout <<t << endl;
        }
        return 0;
    }
  • 相关阅读:
    oo第二次博客作业
    oo第一次博客作业
    软件工程第3次作业 | 提问回顾与个人总结
    软件工程第2次作业 | 结对项目-最长单词链
    软件工程第1次作业 | 第一次阅读
    软件工程第0次作业 | 热身
    OO第四次博客作业
    OO第三次博客作业
    OO第二次博客作业
    OO第一次博客作业
  • 原文地址:https://www.cnblogs.com/hhhhhhhhhhhhhhhhhhhhhhhhhhh/p/3874403.html
Copyright © 2011-2022 走看看