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


 

發佈了49 篇原創文章 · 獲贊 9 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章