您的位置:首页 > 其它

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

2013-10-01 21:44 489 查看
问在第一个串中删掉几个字符能否得到第二个串。注意在第二个串中不连续的单词在第一个串中也必须不连续。

一组数据:

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: