UVA 10391 - Compound Words
链结:戳我。
TLE...看来是Hash Table做的不够好。
View Code
1 /* 2 Author: frankdj 3 State: TLE 4 */ 5 #include <iostream> 6 #include <cstring> 7 #include <cstdio> 8 #include <vector> 9 #include <string> 10 #include <algorithm> 11 using namespace std; 12 13 const int kMaxWordNum = 120001; 14 const int kMaxHashSize = 99991; 15 16 int head[kMaxHashSize], next[kMaxWordNum], word_count[kMaxWordNum]; 17 18 void InitLookupTable() { 19 memset(head, 0, sizeof(head)); 20 memset(next, 0, sizeof(next)); 21 memset(word_count, 0, sizeof(word_count)); 22 } 23 24 int Hash(string str) { 25 int hash_value = 0; 26 for (int i = 0; i < str.length(); i++) { 27 hash_value = (hash_value<<2) + str[i] - 'a' + 1; 28 } 29 return hash_value % kMaxHashSize; 30 } 31 32 void Insert(int index, vector<string> word_list) { 33 int h = Hash(word_list[index]); 34 int u = head[h]; 35 while (u) { 36 if (word_list[index].compare(word_list[u]) == 0) 37 break; 38 u = next[u]; 39 } 40 next[index] = head[h]; 41 head[h] = index; 42 } 43 44 bool StartWith(int index_head, int index_next, vector<string> word_list) { 45 string word_head = word_list[index_head], 46 word_next = word_list[index_next]; 47 if (word_next.compare(0, word_head.length(), word_head) == 0) 48 return true; 49 else 50 return false; 51 } 52 53 bool Find(int index_head, int index_next, vector<string> word_list) { 54 string shorten = word_list[index_next].substr(word_list[index_head].length(), 55 string::npos); 56 int h = Hash(shorten); 57 int u = head[h]; 58 while (u) { 59 if (word_list[u].compare(shorten) == 0) { 60 if (word_count[u] == 0) { 61 word_count[u]++; 62 return true; 63 } 64 else 65 return false; 66 } 67 u = next[u]; 68 } 69 return false; 70 } 71 72 int main(int argc, char *argv[]){ 73 #ifndef ONLINE_JUDGE 74 freopen("input.txt", "r", stdin); 75 #endif 76 77 vector<string> word_list; 78 word_list.push_back(" "); 79 string word = ""; 80 InitLookupTable(); 81 82 while (cin >> word && word.length() != 0) { 83 word_list.push_back(word); 84 } 85 86 sort(word_list.begin(), word_list.end()-1); 87 88 for (int i = 1; i < word_list.size(); i++) { 89 Insert(i, word_list); 90 } 91 92 int index_head = 1, index_next = 2; 93 vector<string> output; 94 while (index_next < word_list.size()) { 95 while (StartWith(index_head, index_next, word_list)) { 96 if (Find(index_head, index_next, word_list)){ 97 output.push_back(word_list[index_next]); 98 } 99 index_next++; 100 } 101 index_head++; 102 index_next = index_head + 1; 103 } 104 105 sort(output.begin(), output.end()-1); 106 107 for (int i = 0; i < output.size(); i++) 108 cout << output[i] << endl; 109 110 return 0; 111 112 }
这里的东西都是自娱自乐的.我只是抱着构思算法的心态去做UVA的题.
我所有的code都不可能AC的.因为我就没想着让它能AC.