hdu 1251统计难题 字典树

题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1251

字典树模版题

动态实现:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define maxn 26
struct node
{
	int count;
	node *next[maxn];
}*root;
void insert(char str[])
{
	int i,len = strlen(str);
	node *current,*newset;
	current = root;
	for(i = 0; i < len; i++)
	{
		int k = str[i] - 'a';
		if(current->next[k] != NULL)
		{
			current = current->next[k];
			current->count++;
		}
		else
		{
			newset = (node*)malloc(sizeof(node));
			memset(newset->next,NULL,sizeof(newset->next));
			current->next[k] =newset;
			current = newset;
			current->count = 1;
		}
	}
}
int find(char str[])
{
	int i,len = strlen(str);
	if(len == 0)
		return 0;
	node *current = root;
	for(i = 0; i < len ; i++)
	{
		int k = str[i] - 'a';
		if(current->next[k] != NULL)
			current = current->next[k];
		else
			return 0;
	}
	return current->count;
}

int main()
{
	char str[101];
	root = (node*)malloc(sizeof(node));
	memset(root->next,NULL,sizeof(root->next));
	while(gets(str) && str[0] != '\0')
		insert(str);
	while(~scanf("%s",str))
		printf("%d\n",find(str));
	return 0;
}


静态实现:

#include<stdio.h>
#include<string.h>
struct node
{
	int cnt;
	node *next[26];
	node()
	{
		cnt = 0;
		memset(next,NULL,sizeof(next));
	}
}tree[400000];
int cnt = 1;
node *root;
void insert(char *str)
{
	node *p = root;
	int m;
	while(*str)
	{
		m = *str- 'a';
		if(p->next[m] == NULL)
			p->next[m] = &tree[cnt++];
		p = p->next[m];
		p->cnt ++;
		str++;
	}
}
int search(char *str)
{
	int m;
	node *p = root;
	while(*str)
	{
		m = *str - 'a';
		if(p->next[m] == NULL)
			return 0;
		p = p->next[m];
		str++;
	}
	return p->cnt;
}
int main()
{
	char str[15];
	root = tree;
	cnt = 1;
	while(gets(str) && str[0] != '\0')
		insert(str);
	while(~scanf("%s",str))
		printf("%d\n",search(str));
	return 0;
}


 

posted @ 2012-09-15 08:16  一生挚爱  阅读(125)  评论(0编辑  收藏  举报