URAL 1732. Ministry of Truth ( KMP 多模式串匹配 )

问在第一个串中删掉几个字符能否得到第二个串。注意在第二个串中不连续的单词在第一个串中也必须不连续。

一组数据:

Input:

abababbbbabab
bb aba ab

Output:

I HAVE FAILED!!!

#include <cstdio>
#include <cstring>
#include <cstdlib>

using namespace std;

const int MAXN = 100100;

char str[MAXN];
char tmp[MAXN];
int nextval[MAXN];
int flag[MAXN];
int strL, tmpL;

void getNextval( char* s, int* nextval, int length )
{
    int i=0,j=-1;
    nextval[0]=-1;
    while(i<length)
    {
        if(j==-1||s[i]==s[j])
        {
            ++i;
            ++j;
            //next[i]=j;
            if (s[i]!=s[j])
                nextval[i]=j;
            else
                nextval[i]=nextval[j];
        }
        else
            j=nextval[j];
    }
}

int KMP( char *t, char *s, int lenth, int len )   //s为主串,t为模式串
{
    getNextval( t, nextval, lenth );
    int i = 0, j = 0;
    while ( j < len )
    {
        if ( i == -1 || s[j] == t[i] )
        {
            ++i, ++j;
            if ( i == lenth ) return j;
        }
        else i = nextval[i];
    }
    return -1;
}

int main()
{
    while ( gets( str ) != NULL )
    {
        strL = strlen(str);
        memset( flag, -1, sizeof(flag) );
        bool ok = true;
        int i = 0;
        while ( 1 )
        {
            scanf( "%s", tmp );
            tmpL = strlen(tmp);

            int ans = KMP( tmp, &str[i], tmpL, strL - i );

            //puts(tmp);
            //puts(&str[i]);

            if ( ans == -1 ) ok = false;
            else flag[ i + ans - tmpL ] = tmpL;

            char ch = getchar();

            if ( ch == '\n' ) break;
            i += ans + 1;
        }
        if ( ok )
        {
            for ( int i = 0; i < strL; ++i )
            {
                if ( str[i] == ' ' ) putchar(' ');
                else if ( flag[i] == -1 ) putchar('_');
                else
                {
                    for ( int j = 0; j < flag[i]; ++j )
                        putchar( str[i+j] );
                    i += flag[i] - 1;
                }
            }
            puts("");
        }
        else puts("I HAVE FAILED!!!");
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/GBRgbr/p/3348835.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值