大致题意:
输入的前半部分为一个最多100000词的字典,每一行一个英文单词和对应的外文单词,英文单词和外文单词用空格分开。输入的后半部分是待翻译的外文单词。输出翻译后的英文单词,如果不能翻译则输出"eh"。
解题思路:
可以将字典存入一个数组中,按照外文单词顺序进行排序,通过二分查找得到对应的英文单词。
C++代码:
#include <iostream> using namespace std; class node{ //key是外文单词,value是英文单词 public: char key[15]; char value[15]; node& operator=(const node &x){ strcpy(key, x.key); strcpy(value, x.value); return *this; } bool operator<=(const node &x){ if(strcmp(key, x.key) <= 0) return true; return false; } bool operator>=(const node &x){ if(strcmp(key, x.key) >= 0) return true; return false; } }; int bi_search(node a[], int low, int high, char key[]){ //二分查找 if(low > high){ if(strcmp(a[high].key, key)==0) return high; else return -1; } int mid = (low + high)/2; if(strcmp(a[mid].key, key) > 0){ high = mid - 1; return bi_search(a, low, high, key); } else{ low = mid + 1; return bi_search(a, low, high, key); } } int partition(node a[], int p, int q){ node pivot = a[p]; while(p < q){ while(p < q && a[q] >= pivot) q--; a[p] = a[q]; while(p < q && a[p] <= pivot) p++; a[q] = a[p]; } a[p] = pivot; return p; } void q_sort(node a[], int p, int q){ //快速排序 if(p >= q) return; int r = partition(a, p, q); q_sort(a, p, r-1); q_sort(a, r+1, q); } int main() { node *nodes = new node[1000010]; char str[15]; int i = 0; while(true){ gets(str); if(strcmp(str, "") == 0){ break; } int pos = strchr(str, ' ') - str; memcpy(nodes[i].value, str, pos); nodes[i].value[pos] = '\0'; memcpy(nodes[i].key, str+pos+1, strlen(str)-pos-1); nodes[i].key[strlen(str)-pos-1] = '\0'; i++; } q_sort(nodes, 0, i-1); while(gets(str) != NULL){ int j = bi_search(nodes, 0, i-1, str); if(j == -1) cout << "eh" << endl; else cout << nodes[j].value << endl; } delete [] nodes; return 0; }