您的位置:首页 > 其它

POJ - 2503 Babelfish

2015-03-29 01:33 295 查看
Babelfish

Time Limit: 3000MSMemory Limit: 65536KB64bit IO Format: %I64d & %I64u
Submit Status

Description

You have just moved from Waterloo to a big city. The people here speak an incomprehensible dialect of a foreign language. Fortunately, you have a dictionary to help you understand them.

Input

Input consists of up to 100,000 dictionary entries, followed by a blank line, followed by a message of up to 100,000 words. Each dictionary entry is a line containing an English word, followed by a space and a foreign language word. No foreign word appears
more than once in the dictionary. The message is a sequence of words in the foreign language, one word on each line. Each word in the input is a sequence of at most 10 lowercase letters.

Output

Output is the message translated to English, one word per line. Foreign words not in the dictionary should be translated as "eh".

Sample Input

dog ogday
cat atcay
pig igpay
froot ootfray
loops oopslay

atcay
ittenkay
oopslay


Sample Output

cat
eh
loops


Hint

Huge input and output,scanf and printf are recommended.

#include<iostream>        //该题用暴力求解会出现Time Limit Exceeded
#include<cstring>         //二分查找是对有序数组的查找 可以优化效率 查找时间为O(lgn)
#include<string>
#include<cstdio>
#include<algorithm>

using namespace std;
const int MAXN = 100100;

struct dii              //用结构体定义字典
{
	char d[25];
	char di[25];
}p[MAXN];

bool cmp(dii a, dii b)   //定义对结构体的比较
{  
	return strcmp(a.di, b.di)<0;
}

int find(int sl, int sr, char target[25])  
{
	int l = sl, r = sr, mid;                 //核心:二分法查找
	while (l <= r)
	{
		mid = (l + r) >> 1;
		if (strcmp(p[mid].di, target) == 0) return mid;   //找到则返回下标
		else if (strcmp(p[mid].di, target)>0) r = mid - 1;     //目标小于中点,改变区间右端在【a,(a+b)/2-1】查找
		else if (strcmp(p[mid].di, target)<0) l = mid + 1;     //目标大于中点,改变区间左端在【(a+b)/2+1,b】查找
	}
	return -1;    //找不到返回-1;
}

int main()
{
	char s[25];
	int i = 0;
	while (gets(s))
	{
		if (s[0] == '\0') break;
		sscanf(s, "%s%s", p[i].d, p[i].di);    //sscanf函数用于读入整行数据
		i++;
	}

	sort(p, p + i, cmp);       //二分查找是在顺序基础上进行的

	char c[25];
	while (cin >> c)
	{
		int ans = find(0, i - 1, c);
		if (ans == -1) cout << "eh" << endl;
		else cout << p[ans].d << endl;
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: