HDU-3746-Cyclic nacklace (KMP, circular section)

link:

https://vjudge.net/problem/HDU-3746

Meaning of the questions:

The first question coming.

You are given a string, ask how many characters the least added to the end of the string, the string can make this repeat cycle sequence is obtained.

Ideas:

Consider a string of length len, and by the length l substring circulating composition.
We have S [0, len-l- 1] = S [l, len], the number of cycles at the time of greater than 2,
so len -. length Next [len] is the smallest section of the circulating
paint understand like FIG.

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;

int Next[MAXN];
string s, p;

void GetNext()
{
    int len = p.length();
    Next[0] = -1;
    int j = 0;
    int k = -1;
    while (j < len)
    {
        if (k == -1 || p[k] == p[j])
        {
            ++k;
            ++j;
            Next[j] = k;
        }
        else
            k = Next[k];
    }
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int t;
    cin >> t;
    while (t--)
    {
        cin >> p;
        GetNext();
        int len = p.length()-Next[p.length()];
        if (len != p.length() && p.length()%len == 0)
            cout << 0 << endl;
        else
            cout << len-(p.length()%len) << endl;
    }

    return 0;
}

Guess you like

Origin www.cnblogs.com/YDDDD/p/11578717.html