hihocoder 1014 Trie树 字典树模版题

题目连接:http://hihocoder.com/problemset/problem/1014


第一次写字典树,首先写了个顶部没有空结点的字典树,- -!!,与别人讨论后发现这样实在是太奇怪了,随后写了个标准一点的字典树,开帖记录。。。

ps:上面的那个网站挺不错的,验证模版什么的太方便了。


第一次代码:

#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

struct Trie;

struct node{
	int cnt;
	Trie *next;
	
	node(){cnt = 0; next = NULL;}
};

struct Trie{
	node a[26];
	
	Trie(){}
	
	void insert(char *word);
	int find(char *word);
};

void Trie::insert(char *word){
	Trie *p = this; 
	int i;
	for(i = 0; i < strlen(word)-1; i++){
		if(p->a[word[i]-'a'].next == NULL){
			p->a[word[i]-'a'].next = new Trie;
		}
		p->a[word[i]-'a'].cnt++;
		p = p->a[word[i]-'a'].next;
	}
	p->a[word[i]-'a'].cnt++;
	
}

int Trie::find(char *word){
	Trie *p = this; 
	int i;
	for(i = 0; i < strlen(word)-1; i++){
		p = p->a[word[i]-'a'].next;
		if(p == NULL) return 0;
	}
	return p->a[word[i]-'a'].cnt;
}

int n,m;
char s[30];

int main(){
	Trie t;
	scanf("%d",&n);
	for(int i = 0; i < n; i++){
		scanf("%s",s);
		t.insert(s);
	}
	scanf("%d",&m);
	for(int i = 0; i < m; i++){
		scanf("%s",s);
		printf("%d\n",t.find(s));
	}
	return 0;
}

第二次代码:

#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;


struct Trie{
	Trie *a[26];
	int cnt;
	
	Trie(){
		for(int i = 0; i < 26; i++) a[i] = NULL;
		cnt = 0;
	}
	
	void insert(char *word);
	int find(char *word);
};

void Trie::insert(char *word){
	Trie *p = this; 
	int i;
	for(i = 0; i < strlen(word); i++){
		if(p->a[word[i]-'a'] == NULL){
			p->a[word[i]-'a'] = new Trie;
		}
		p = p->a[word[i]-'a'];
		p->cnt++;
	}
	
}

int Trie::find(char *word){
	Trie *p = this; 
	int i;
	for(i = 0; i < strlen(word); i++){
		p = p->a[word[i]-'a'];
		if(p == NULL) return 0;
	}
	return p->cnt;
}

int n,m;
char s[30];

int main(){
	Trie t;
	scanf("%d",&n);
	for(int i = 0; i < n; i++){
		scanf("%s",s);
		t.insert(s);
	}
	scanf("%d",&m);
	for(int i = 0; i < m; i++){
		scanf("%s",s);
		printf("%d\n",t.find(s));
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值