UVA 644 - Immediate Decodability

判断一组code当中有没有其中一个是另一个的前缀,如果有的话就不是immediately decodable ,

反正则是。我们首先要将每组字符串单独取出来进行排序,按照由短到长,相同长度按字典序排序。

排序之后用靠前的字符串与靠后的比较。

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

#define MAXN 20

char co[MAXN][15], str[15];

int cmp( const void *_a, const void *_b)
{
char *a = ( char *)_a;
char *b = ( char *)_b;
if( strlen( a) > strlen( b)) return 1;
else if( strlen( a) < strlen(b) ) return -1;
return strcmp( a, b);
}

bool decode( int n)
{
char c[10];
memset( c, 0, sizeof c);
for( int i = 0; i < n - 1; i ++)
for( int j = i + 1; j < n; j ++)
{
int len = strlen( co[i]);
for( int k = 0; k < len; k ++)
c[k] = co[j][k];
if( strcmp(c, co[i]) == 0) return false;
}
return true;
}

int main()
{
int n = 0, cas = 1;
while( gets( str) != NULL)
{
if( str[0] != '9')
{
memset( co[n], 0, sizeof( co[n]));
strcpy( co[n], str);
n ++;
}
if( str[0] == '9') {
qsort( co, n, sizeof( co[0]), cmp);
if( decode( n))
printf( "Set %d is immediately decodable\n", cas ++);
else
printf( "Set %d is not immediately decodable\n", cas ++);
n = 0;
}
}
return 0;
}

 

你可能感兴趣的:(media)