POJ 2503 Babelfish(字典树)

题目链接:http://poj.org/problem?id=2503


题意:翻译单词,若在词典中找不到则输出eh。


思路:裸的字典树。


代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <string>
#include <vector>

using namespace std;

#define lson l, m, rt << 1
#define rson m + 1, r, rt << 1 | 1
#define ceil(x, y) (((x) + (y) - 1) / (y))

const int SIZE = 30;
const int N = 3e6 + 10;
const int INF = 0x7f7f7f7f;
const int MAX_WORD = 30;
const int M = 1e5 + 10;

struct Trie {
	int w;
	int val[SIZE];
};

int sz;
Trie pn[N];
char word[M][MAX_WORD];

int newnode() {
	memset(pn[sz].val, 0, sizeof(pn[sz].val));
	pn[sz].w = 0;
	return sz++;
}

void init() {
	sz = 0;
	newnode();
	strcpy(word[0], "eh");
}

void insert(char *s, int t) {
	int u = 0;
	for (int i = 0; s[i]; i++) {
		int idx = s[i] - 'a';
		if (!pn[u].val[idx])
			pn[u].val[idx] = newnode();
		u = pn[u].val[idx];
	}
	pn[u].w = t;
}

int findstr(char *s) {
	int u = 0;
	for (int i = 0; s[i]; i++) {
		int idx = s[i] - 'a';
		if (!pn[u].val[idx])
			return 0;
		u = pn[u].val[idx];
	}
	return pn[u].w;
}

int main() {
	char s[MAX_WORD], t[MAX_WORD];
	init();
	int i_n = 1;
	while (gets(s) && s[0] != '\0') {
		int k = 0;
		bool flag = false;
		for (int i = 0; s[i]; i++) {
			if (flag)
				t[k++] = s[i];
			if (s[i] == ' ') {
				s[i] = '\0';
				flag = true;
			}
		}
		t[k] = '\0';
		insert(t, i_n);
		strcpy(word[i_n++], s);
	}
	while (gets(s))
		puts(word[findstr(s)]);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值