poj2503-Babelfish(快速排序+二分查找)

大致题意:  

 输入的前半部分为一个最多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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值