J - Just a Magic String

Posted 季末Despaire

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了J - Just a Magic String相关的知识,希望对你有一定的参考价值。

J - Just a Magic String

Time Limit: 1000/1000MS (Java/Others)     Memory Limit: 131072/131072KB (Java/Others)

Description

You have such a string $S$ a, every time you can copy $S$ to $T$ ,change a in $T$ to bb to a, then add $T$ after $S$.

For example,

a

ab

abba

abbabaab

abbabaabbaababba

......

Finally you will get a infinite magic string.

Now, given a string $X$ only containing a and b, you should tell me if it appears in the magic string?

If it appears, than output the location it first appears, otherwise, output -1;

Input

A line with a string that consists only a and b and no more than $10^6$ characters.

Output

Print the position of the first occurrence of the string, or -1 if it doesn‘t exist.

Sample input 

bab

Sample output

3

Sample input

baab

Sample output

5

Sample input

aaabbb

 

Sample output

-1

 

总结

想了半天不知道怎么做,结果还是楚枫说的kmp算法来解决的

 

#include<iostream>
#include<string>
#include<vector>
using namespace std;
int kmp_find(const string& target,const string& pattern)
{
    const int target_length = target.size();
    const int pattern_length = pattern.size();
    int * overlay_value = new int[pattern_length];
    overlay_value[0] = -1;
    int index = 0;
    for(int i=1;i<pattern_length;++i)
    {
        index = overlay_value[i-1];
        while(index>=0 && pattern[index+1]!=pattern[i])
        {
            index  = overlay_value[index];
        }
        if(pattern[index+1]==pattern[i])
        {
            overlay_value[i] = index +1;
        }
        else
        {
            overlay_value[i] = -1;
        }
    }
    //match algorithm start
    int pattern_index = 0;
    int target_index = 0;
    while(pattern_index<pattern_length&&target_index<target_length)
    {
        if(target[target_index]==pattern[pattern_index])
        {
            ++target_index;
            ++pattern_index;
        }
        else if(pattern_index==0)
        {
            ++target_index;
        }
        else
        {
            pattern_index = overlay_value[pattern_index-1]+1;
        }
    }
    if(pattern_index==pattern_length)
    {
        return target_index-pattern_index;
    }
    else
    {
        return -2;
    }
    delete [] overlay_value;
}
int main()
{
    string source="a";
    string a=source;
    string pattern;
    int n=25;

    cin >>pattern;

    for(int i=1;i<=n;i++){
        a=source;
        for(int j=0;j<a.length();j++){
            if(a[j]==a) a[j]=b;
            else a[j]=a;
        }
        source+=a;
    }
    cout<<kmp_find(source,pattern)+1<<endl;
    return 0;
}

 

 

 

 

以上是关于J - Just a Magic String的主要内容,如果未能解决你的问题,请参考以下文章

codeforces 632F. Magic Matrix

hdu 4790 Just Random 锛?013鎴愰兘J棰橈級 鏁板鎬濊矾棰?瀹规枼

HDU6655 Just Repeat(2019杭电多校J题)

ZOJ 2974 Just Pour the Water

hdu 6129 Just do it

HDU 5942 Just a Math Problem 2016 杭州 CCPC 最大质数间隔777