HDU-4763-Theme Section (KMP)

link:

http://acm.hdu.edu.cn/showproblem.php?pid=4763

Meaning of the questions:

It's time for music! A lot of popular musicians are invited to join us in the music festival. Each of them will play one of their representative songs. To make the programs more interesting and challenging, the hosts are going to add some constraints to the rhythm of the songs, i.e., each song is required to have a 'theme section'. The theme section shall be played at the beginning, the middle, and the end of each song. More specifically, given a theme section E, the song will be in the format of 'EAEBE', where section A and section B could have arbitrary number of notes. Note that there are 26 types of notes, denoted by lower case letters 'a' - 'z'.

To get well prepared for the festival, the hosts want to know the maximum possible length of the theme section of each song. Can you help us?

Ideas:

Next KMP resulting array,
consider the original string is equal to the prefix string of all suffixes, find the same in the middle part,
determines whether or not Next [i] = len, where len indicates the prefix length.
Next array or to learn more about.

Code:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
//#include <memory.h>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
#include <math.h>
#include <stack>
#include <string>
#include <assert.h>
#include <iomanip>
#include <iostream>
#include <sstream>
#define MINF 0x3f3f3f3f
using namespace std;
typedef long long LL;
const int MAXN = 1e6+10;

char s[MAXN];
int Next[MAXN];

void GetNext(char *ori)
{
    int len = strlen(ori);
    int j = 0, k = -1;
    Next[0] = -1;
    while (j < len)
    {
        if (k == -1 || ori[j] == ori[k])
        {
            ++j;
            ++k;
            Next[j] = k;
        }
        else
            k = Next[k];
    }
}

int main()
{
    int t;
    scanf("%d", &t);
    while (t--)
    {
        scanf("%s", s);
        GetNext(s);
        int len = strlen(s);
        int ml = Next[len];
        while (ml > 0)
        {
            int flag = false;
            for (int i = ml*2;i <= len-ml;i++)
            {
                if (Next[i] == ml)
                {
                    flag = true;
                    break;
                }
            }
            if (flag)
                break;
            ml = Next[ml];
        }
        printf("%d\n", ml);
    }

    return 0;
}

Guess you like

Origin www.cnblogs.com/YDDDD/p/11606754.html
Recommended