您的位置:首页 > 其它

HDU 1075 What Are You Talking About(字典树)

2015-08-17 22:52 537 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1075

题意:根据词典翻译语句。

思路:裸的字典树。每个节点存以该节点为结尾的对应的单词。

代码:

#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 = 3000 * 10 * 26 + 10;
const int INF = 0x7f7f7f7f;
const int MAX_WORD = 15;

struct Trie {
	char word[MAX_WORD];
	int val[SIZE];
};

int sz;
Trie pn
;

int newnode() {
	memset(pn[sz].val, 0, sizeof(pn[sz].val));
	strcpy(pn[sz].word, "#");
	return sz++;
}

void init() {
	sz = 0;
	newnode();
}

void insert(char *s, char *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];
	}
	strcpy(pn[u].word, t);
}

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

int main() {	
	char s[3005], t[MAX_WORD];
	init();
	while (scanf("%s", s) && s[0] != 'E') {
		if (s[0] == 'S')
			continue;
		scanf("%s", t);
		insert(t, s);
	}
	getchar();
	while (gets(s) && s[0] != 'E') {
		if (s[0] == 'S')
			continue;
		int len = strlen(s);
		int l = -1;
		for (int i = 0; i < len; i++) {
			if (s[i] >= 'a' && s[i] <= 'z') {
				if (l == -1)
					l = i;
				else if (i == len - 1) {
					char *p = findstr(s, l, i);
					if (p != NULL && p[0] != '#')
						printf("%s", p);
					else {
						for (int j = l; j <= i; j++)
							printf("%c", s[j]);
					}
				}
			}
			else {
				if (l == -1)
					printf("%c", s[i]);
				else {
					char *p = findstr(s, l, i - 1);
					if (p != NULL && p[0] != '#')
						printf("%s", p);
					else {
						for (int j = l; j < i; j++)
							printf("%c", s[j]);
					}
					printf("%c", s[i]);
					l = -1;
				}
			}
		}
		printf("\n");
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: