zoukankan      html  css  js  c++  java
  • 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;
    }
    


     

  • 相关阅读:
    分子量 (Molar Mass,ACM/ICPC Seoul 2007,UVa 1586)
    [补档]各种奇怪的韩信问题
    [补档][HNOI 2008]GT考试
    [补档][Tyvj 1728]普通平衡树
    [补档][JLOI 2017]聪明的燕姿
    [补档][NOI 2008]假面舞会
    网络基础
    操作系统
    计算机硬件
    类和对象
  • 原文地址:https://www.cnblogs.com/LUO257316/p/3220828.html
Copyright © 2011-2022 走看看