Algorithm competition entry classic 5.32 sorting and retrieval-letter arrangement and retrieval sorting
Enter a dictionary (ending with ******), and then enter several words. Every time you enter a word w, you need to find all the words in the dictionary that can be rearranged with w letters, and output in a row in ascending Lexicographic Order (if not, output :(). Words are separated by spaces or blank lines. All words can contain up to 6 lowercase letters. Note that words in the dictionary are not necessarily listed in Lexicographic Order.
1 # include <stdio. h> 2 # include <stdlib. h> 3 # include <string. h> 4 int n; 5 char word [2000] [10], sorted [2000] [10]; 6 // character comparison function 7 int cmp_char (const void * _, const void * _ B) 8 {9 char * a = (char *) _ a; 10 char * B = (char *) _ B; 11 return * a-* B; 12} 13 14 // string comparison function 15 int cmp_string (const void * _ a, const void * _ B) 16 {17 char * a = (char *) _; 18 char * B = (char *) _ B; 19 return strcmp (a, B); 20} 21 22 int main () 23 {24 n = 0; 25 for (;) 26 {27 scanf ("% s", word [n]); 28 if (word [n] [0] = '*') break; // terminate the loop if the end sign is met. 29 n ++; 30} 31 qsort (word, n, sizeof (word [0]), cmp_string); // sort all words by 32 for (int I = 0; I <n; I ++) 33 {34 strcpy (sorted [I], word [I]); 35 qsort (sorted [I], strlen (sorted [I]), sizeof (char), cmp_char ); // sort each word 36} 37 char s [10]; 38 while (scanf ("% s", s) = 1) // read 39 {40 qsort (s, strlen (s), sizeof (char), c Mp_char); // sort the input words by 41 int found = 0; 42 for (int I = 0; I <n; I ++) 43 if (strcmp (sorted [I], s) = 0) 44 {45 found = 1; 46 printf ("% s", word [I]); // output the original word instead of the sorted 47} 48 if (! Found) printf (":("); 49 printf ("\ n"); 50} 51 return 0; 52}View Code
Analysis:
1. steps:
Step 1: first, sort all words in the dictionary (make sure that the words in the dictionary are listed in Lexicographic Order), and save the results in the sorted array;
Step 2: Sort each word in the dictionary (avoid every shuffling );
Step 3: each time you read a word, sort the letters of the word and directly compare it with all the words in the dictionary to determine whether the two words can be obtained through rearrangement;
Step 4: output the original words in the dictionary immediately when a word meets the conditions.
2. The program uses the sqort sorting function in <stdlib. h>. Although the amount of code sorted by the library function is not smaller than the Bubble sorting method, it is much faster.