POJ 2530 解题报告 trie 树

这篇博客分享了POJ 2530题目的解题思路,主要利用trie树解决字符串映射查询问题。内容涉及如何使用trie树进行高效查找,并提供了相关代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目意思:

给含有两个单词的映射关系的字典,然后查询接下来每个输入字符串的对应字符串。


这题可以用 hash 或者 trie 树,都是入门级别。


代码:

//这题是 trie 树 和 哈希 的入门题。
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <cstring>
using namespace std;

#define maxn 100010

typedef struct node {
	char word[12];
	int childs[26];
	void init() { memset(childs, -1, sizeof(childs)); }
} Node;

Node ns[maxn * 10];
char ew[12], fw[12];
int node_num;
int root;

void insert(char *e, char *f)
{
	int r = 0, index;
	for (int i = 0; f[i] != '\0'; ++i) {
		index = f[i] - 'a';
		if (ns[r].childs[index] == 0) {
			ns[r].childs[index] = ++node_num;
			r = node_num;
		}
		else 
		r = ns[r].childs[index];
	}
	strcpy(ns[r].word, e);
}

void query(char *f)
{
	int r = 0, index;
	for (int i = 0; f[i] != '\0'; ++i) {
		index = f[i] - 'a';
		if (ns[r].childs[index] == 0) {
			printf("eh\n");
			return;
		}
		else {
			r = ns[r].childs[index];
		}
	}
	printf("%s\n", ns[r].word);
	return;
}

int main()
{
	//freopen("testdata/2503.txt", "r", stdin);
	node_num = 0;
	string s;
	while (getline(cin, s)) { //输入还用 fgets + sscanf 会快一大半。
		if (s.length() > 0) {
			istringstream stream(s);
			stream >> ew >> fw;
			insert(ew, fw);
		}
		else
			break;
	}
	while (scanf("%s", fw) != EOF)  query(fw);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值