1251 hdu 字典树

题源连接:http://acm.hdu.edu.cn/showproblem.php?pid=1251

字典树的模板套用,思路在代码里面,如下:

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

using namespace std;

struct Node
{
        int num;//记录到该字符有几个前缀相同的字符串。
        Node* pNext[26];
        Node()//初始化
        {
                memset(pNext, NULL, sizeof(pNext));
                num = 0;
        }
};

Node* pRoot;
void Insert( char *str )
{
        Node *p, *pNewNode;
        p = pRoot;
        for(; *str; str++)//插入字符串操作
        {
                if(p->pNext[ *str - 'a' ] != NULL)//如果在相同的前缀下,p->num就要加1;仔细体会一下,在纸上画画就会明白
                {
                        p = p->pNext[ *str - 'a' ];
                        p->num++;
                }
                else
                {
                        pNewNode = new Node;
                        p->pNext[ *str-'a' ] = pNewNode;
                        p = p->pNext[ *str - 'a' ];
                        p->num = 1;
                }
        }
}

int Find( char *str )
{
        Node *p;
        p = pRoot;
        for(; *str; str++)
        {
                if(p->pNext[*str - 'a'] != NULL)//找到了,顺着树枝走下去。
                        p = p->pNext[ *str - 'a' ];
                else
                        return 0;
        }
        return p->num;
}

void DeleteTree(Node *pRoot)
{
	int i = 0;
	Node* p = pRoot;
	for(;i < 26;++i)
	{
		if(p->pNext[i])
			DeleteTree(p->pNext[i] );
	}
	delete(p);
}

int main()
{
        char a[15];
        pRoot = new Node;
        while( gets(a) )//建字典树
        {
                if(strlen(a) == 0)
                        break;
                Insert( a );
        }
        while( gets(a) )//查询
                cout<<Find(a)<<endl;
		DeleteTree(pRoot);
        return 0;
}


你可能感兴趣的:(trie)