#include <iostream>

using namespace std;

typedef struct

{

    char ch[1000];

    int length;

} SString;

void get_next(SString T, int next[])

{

    int i = 1, j = 0;

    next[1] = 0;

    cout << "选择next[],请按1;选择nextval,请按2:   ";

    int F;

    cin >> F;

    while (i < T.length)

    {

        if (F == 2)

            break;

        if (j == 0 || [i] == [j])

        {

            i++;

            j++;

            next[i] = j;

        }

        else

            j = next[j];

    }

    while (i < T.length)

    {

        if (F == 1)

            break;

        if (j == 0 || [i] == [j])

        {

            i++;

            j++;

            if ([i] != [j])

                next[i] = j;

            else

                next[i] = next[j];

        }

        else

            j = next[j];

    }

}

void Index_KMP(SString S, SString T, int pos)

{

    int i = pos, j = 1, next[1000];

    get_next(T, next);

    while (i <= S.length && j <= T.length)

    {

        if (j == 0 || [i] == [j])

        {

            i++;

            j++;

        }

        else

            j = next[j];

    }

    if (j > T.length)

        cout << "从第" << i - T.length << "处开始匹配" << endl;

    else

        cout << "模式串与主串不匹配" << endl;

}

int main()

{

Loop:

    cout << "__________________________________________" << endl;

    cout << "******************************************" << endl;

    cout << "__________________________________________" << endl;

    cout << endl;

    SString S, T;

    S.length = 0;

    T.length = 0;

loop1:

    cout << "输入主串的长度(n>=1): ";

    int i, n;

    char data;

    cin >> n;

    S.length = n;

    cout << "输入主串元素" << endl;

    cout << "输入过程中按0退出本次输入" << endl;

    cout << "主串元素:";

    for (i = 1; i <= n; i++)

    {

        cin >> data;

        if (data - 97 >= 0)

            [i] = data;

        else

            goto loop1;

    }

loop2:

    cout << "输入模式串的长度(n>=1):";

    cin >> n;

    T.length = n;

    cout << "输入模式串元素" << endl;

    cout << "输入过程中按0退出本次输入" << endl;

    cout << "模式串元素:";

    for (i = 1; i <= n; i++)

    {

        cin >> data;

        if (data - 97 >= 0)

            [i] = data;

        else

            goto loop2;

    }

    int pos;

    cout << "输入检索位置(pos>=1):";

    cin >> pos;

    Index_KMP(S, T, pos);

    cout << "继续检索请按1;退出检索请按0" << endl;

    int F;

    cin >> F;

    if (F)

        goto Loop;

    else

        cout << "\t\t谢谢使用" << endl;

    cout << "------------------------------------------" << endl;

    return 0;

}