UVA 188 - Perfect Hash
链结:戳我。
AC了。其实就是如果C是不符合要求的,按照公式求一次,然后再代回去检验看一下行不行。
如果可以就输出;
不行的话就Refresh一下C的值,然后再重头开始检验。
View Code
1 /* 2 Author: frankdj 3 State: AC 4 Method: Simple conduct step by step what the problem said 5 */ 6 7 #include <iostream> 8 #include <cstring> 9 #include <cstdio> 10 #include <algorithm> 11 using namespace std; 12 13 const int MAXIN = 100; 14 const int MAXLENGTH = 14; 15 const int MAXWORD = 6; 16 17 18 void convert_integer(int words[], char word[], int& n_word) { 19 int length = strlen(word), rep = 0; 20 for (int i = 0; i < length; i++){ 21 int index = word[i] - 'a' + 1; 22 rep = (rep<<5) + index; 23 } 24 words[n_word] = rep; 25 n_word++; 26 } 27 28 int compare(const void* a, const void* b) { 29 return (*((int*)a)) - (*((int*) b)); 30 } 31 32 int find(int words[], int n_word) { 33 int c = words[0]; 34 bool is_changed = true, is_found = false; 35 while (is_changed){ 36 is_changed = false; 37 for (int i = 0; !is_changed && i < n_word; i++){ 38 int hash_i = (c/words[i]) % n_word; 39 40 for (int j = i+1; !is_changed && j < n_word; j++){ 41 int hash_j = (c/words[j]) % n_word; 42 if (hash_i == hash_j){ 43 is_changed = true; 44 c = min((c/words[i]+1)*words[i], 45 (c/words[j]+1)*words[j]); 46 } 47 } 48 } 49 } 50 return c; 51 } 52 53 54 int main(int argc, char *argv[]){ 55 56 #ifndef ONLINE_JUDGE 57 freopen("input.txt", "r", stdin); 58 //freopen("output.txt", "w", stdout); 59 #endif 60 int n_word, C; 61 int words[MAXLENGTH]; 62 char line[MAXIN], word[MAXWORD]; 63 64 memset(line, 0, sizeof(line)); 65 while (cin.getline(line, MAXIN) && line[0] != EOF){ 66 memset(words, 0, sizeof(words)); 67 C = n_word = 0; 68 69 int length = strlen(line); 70 for (int i = 0; i < length; i++){ 71 memset(word, 0, sizeof(word)); 72 while (line[i] == ' ' || line[i] == '\0') 73 i++; 74 int counter = 0; 75 while (isalpha(line[i])) 76 word[counter++] = line[i++]; 77 78 convert_integer(words, word, n_word); 79 } 80 qsort(words, n_word, sizeof(int), compare); 81 C = find(words, n_word); 82 cout << line << endl; 83 cout << C << endl << endl; 84 85 } 86 return 0; 87 }
这里的东西都是自娱自乐的.我只是抱着构思算法的心态去做UVA的题.
我所有的code都不可能AC的.因为我就没想着让它能AC.