一個字符串處理的問題,做法是排序+二分查找。地址:http://acm.pku.edu.cn/JudgeOnline/problem?id=1318
#include < stdio.h >

#include < stdlib.h >

#include < string.h >

typedef struct


{
char unch[8];
char ch[8];
}type;
type word[101];

int cmp1 ( const void *a, const void *b )


{

return *( char * )a - *( char * )b;
}

int cmp2 ( const void *a, const void *b )


{

type *c = ( type * )a;
type *d = ( type * )b;
int ans;

ans = strcmp ( c->ch, d->ch );
if ( !ans )

{
return strcmp ( c->unch, d->unch );
}
return ans;
}

void sort ( int n )


{

for ( int i=0; i<n; i++ )

{
qsort ( word[i].ch, strlen( word[i].ch ), sizeof( char ), cmp1 );
}

qsort ( word, n, sizeof( type ), cmp2 );
}

int main ()


{

char input[8];
char end[] = "XXXXXX";
int n;
type in;

n = 0;
while ( scanf ( "%s", input ) != EOF && strcmp( input, end ) )

{
strcpy ( word[n].unch, input );
strcpy ( word[n].ch, input );
n ++;
}

sort ( n );

while ( scanf ( "%s", input ) != EOF && strcmp( input, end ) )

{
int left, right, middle;
left = 0; right = n-1;
strcpy ( in.unch, input );
strcpy ( in.ch, input );
qsort ( in.ch, strlen ( in.ch ), sizeof( char ), cmp1 );

while ( left <=right )

{
middle = ( left + right ) / 2;
if ( strcmp ( word[middle].ch, in.ch ) >=0 )

{
right = middle - 1;
}
else

{
left = middle + 1;
}
}

if ( left < n && ( ! strcmp ( word[left].ch, in.ch ) ) )

{
int low, high;
low = left; high = left;
while ( low > 0 && ( ! strcmp ( word[low - 1].ch, in.ch ) ) )

{
low --;
}
while ( high < n-1 && ( ! strcmp ( word[high+1].ch, in.ch ) ) )

{
high ++;
}
for ( ; low<=high; low ++ )

{
printf( "%s\n", word[low].unch );
}
}
else

{
printf ( "NOT A VALID WORD\n" );
}
printf ( "******\n" );
}

return 0;
}


















































































































































