问在第一个串中删掉几个字符能否得到第二个串。注意在第二个串中不连续的单词在第一个串中也必须不连续。
一组数据:
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 == ' ' ) 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; }