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;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值