《算法竞赛入门经典》5.3.2的题目,题目大意:输入一个字典,然后再输入若干单词。每输入一个单词w,你都需要在字典中找出所有可以用w的字母重排后得到的单词,并按照字典序从小到大的顺序输出。代码如下:
View Code
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 5 char dict[110][8], sorted_dict[110][8]; 6 7 int cmp_char(const void * _a, const void * _b) 8 { 9 char * a = (char *)_a; 10 char * b = (char *)_b; 11 return *a - *b; 12 } 13 14 int cmp_string(const void * _a, const void * _b) 15 { 16 char * a = (char *)_a; 17 char * b = (char *)_b; 18 return strcmp(a, b); 19 } 20 21 int main() 22 { 23 #ifdef LOCAL 24 freopen("in", "r", stdin); 25 #endif 26 int n = 0; 27 int i; 28 while(scanf("%s", dict[n++]) != EOF) 29 { 30 if(strcmp(dict[n-1], "XXXXXX") == 0) break; 31 } 32 qsort(dict, n, sizeof(dict[0]), cmp_string); 33 for(i = 0; i < n; i++) 34 { 35 strcpy(sorted_dict[i], dict[i]); 36 qsort(sorted_dict[i], strlen(sorted_dict[i]), sizeof(char), cmp_char); 37 } 38 char s[10]; 39 while(scanf("%s", s) != EOF) 40 { 41 if(strcmp(s, "XXXXXX") == 0) break; 42 qsort(s, strlen(s), sizeof(char), cmp_char); 43 int ok = 0; 44 for(i = 0; i < n; i++) 45 if(strcmp(s, sorted_dict[i]) == 0) 46 { 47 printf("%s\n", dict[i]); 48 ok = 1; 49 } 50 if(!ok) printf("NOT A VALID WORD\n"); 51 printf("******\n"); 52 } 53 return 0; 54 }