poj 1056 IMMEDIATE DECODABILITY(KMP)

时间:2023-12-18 14:39:56

题目链接:http://poj.org/problem?id=1056

思路分析:检测某字符串是否为另一字符串的前缀,数据很弱,可以使用暴力解法。这里为了练习KMP算法使用了KMP算法。

代码如下:

#include <iostream>
using namespace std; const int N = ;
const int Len = ;
char A[N][Len];
int Next[N][Len]; void get_nextval( char P[], int Next[] )
{
int i = , j = -;
int PLen = strlen(P); Next[] = -;
while ( i < PLen - )
{
if ( j == - || P[i] == P[j] )
{
i++;
j++;
if ( P[i] == P[j] )
Next[i] = j;
else
Next[i] = Next[j];
}
else
j = Next[j];
}
} int KMP_Matcher( char T[], char P[], int Next[] )
{
int i = , j = ;
int TLen = strlen( T );
int PLen = strlen( P ); while ( i < TLen && j < PLen )
{
if ( j == - || T[i] == P[j] )
{
i++;
j++;
}
else
j = Next[j];
} if ( j == PLen )
return i - j;
else
return -;
} int main( )
{
int Count = , flag = -, n = ; while ( scanf( "%s\n", A[Count] ) != EOF )
{
if ( A[Count][] == '' )
{
n++;
for( int i = ; i < Count; ++i )
get_nextval( A[i], Next[i] ); for ( int i = ; i < Count - ; ++i )
for ( int j = i + ; j < Count; ++j )
{
if ( flag == )
break;
flag = KMP_Matcher( A[j], A[i], Next[i] );
} if ( flag == )
printf( "Set %d is not immediately decodable\n", n );
else
printf( "Set %d is immediately decodable\n", n ); Count = ;
flag = -;
continue;
} Count++;
} return ;
}