hdu 2846-字典树

建立字典,查找单词。很容易想到字典树。

字典树是用空间换时间。所以空间消耗极大。

另外这个题目有一些不同之处:

1.要计算的是所求单词在字典中的字符串中出现的次数,不一定要从第一个字母出现,字符串中包含所求单词也可以

2.同一个字符串中出现两个相同的字串,只算出现一次

(可见实例中的“d”)


AC代码:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

#define NULL 0

const int num_chars = 26;


struct trieNode
{
	char* data;
	trieNode* branch[num_chars];
	int num;    //在字典中,记录该字符串已经出现的次数,即题目所求
	int mark;   //用于标记同一个单词中的重复字符串
	trieNode(){
		data = NULL;
		num = 0;
		mark = 0;
		for (int i = 0; i < num_chars; i++){
			branch[i] = NULL;
		}
	}
};

trieNode* root;

int insert(char* word){
	int result = 1, position = 0;
	if (root == NULL)    //如果是第一次插入,先建树
		root = new trieNode;
	int char_code;
	trieNode* location = root;
	while (*word != '\0'){        //当单词全部输入遍历完之后,退出循环
		char_code = *word - 'a';
		if (location->branch[char_code] == NULL)     //如果该字串是第一次在字典中出现,则先new
			location->branch[char_code] = new trieNode;
		location = location->branch[char_code];
		position++;
		word++;
		if (location->mark == 0){   //如果这个字串是第一次在该字符串中出现,则记录加一,并且标记,如果同一个字符串再出现同样的字串,则不加1
			location->num++;
			location->mark = 1;
		};
	}
	/*if (location->data != NULL){
		if (location->mark == 0){
			location->num++;
			location->mark = 1;
		}
		return 0;
	}	
	else{
		if (location->mark == 0){
			location->num++;
			location->mark = 1;
		}
	}*/
	return result;
}

int search(char* word){
	int position = 0;
	int char_code;
	trieNode *location = root;
	while (location != NULL && *word != '\0'){
		char_code = *word - 'a';
		location = location->branch[char_code];
		position++;
		word++;
	}
	if (location == NULL){
		return 0;
	}
	return location->num;
}

void frash(char* word){  //刷新标记,便于判断下一个字符串
	int position = 0;
	int char_code;
	trieNode *location = root;
	while (location != NULL && *word != '\0'){
		char_code = *word - 'a';
		location = location->branch[char_code];
		location->mark = 0;
		position++;
		word++;
	}
	if (location != NULL){
		location->mark = 0;
	}
}

int main(){
//	freopen("TestDate.txt", "r", stdin);
	int n, m;
	cin >> n;
	char d[21];
	while (n--){
		cin >> d;
		char* ds = d; 
		while (*ds != '\0'){  //由于是包含关系,所以要将字符串的每一个字母做开头都加入树中
			insert(ds);
			ds++;
		}
		ds = d;
		while (*ds != '\0'){
			frash(ds);
			ds++;
		}
	}
	cin >> m;
	while (m--){
		cin >> d;
		cout << search(d) << endl;
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值