HDU 1671 Phone List(字典树)

  字典树,注意释放内存,否则MLE

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
char a[10010][20];
struct node
{
    int num;
    node *childs[10];
    node()
    {
        num = 0;
        for(int i = 0; i < 10; i++)
            childs[i] = NULL;
    }
};
node *root = new node;
node *nownode,*newnode;
void Insert(char *str)
{
    nownode = root;
    int lens = strlen(str);
    for(int i = 0; i < lens; i++)
    {
        int m = str[i] - '0';
        if(nownode->childs[m] != NULL)
        {
            nownode = nownode->childs[m];
            nownode->num++;
        }
        else
        {
            newnode = new node;
            ++newnode->num;
            nownode->childs[m] = newnode;
            nownode = nownode->childs[m];
        }
    }
}
int Find(char *str)
{
    nownode = root;
    int lens = strlen(str);
    for(int i = 0; i < lens; i++)
    {
        int m = str[i] - '0';
        nownode = nownode->childs[m];
    }
    return nownode->num;
}
void del(node *root)
{
    for(int i=0; i<10; i++)
    {
        if(root->childs[i]!=NULL)
        {
            del(root->childs[i]);
        }
    }
    delete(root);
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n;
        root = new node;
        scanf("%d",&n);
        for(int i = 0; i < n; i++)
        {
            scanf("%s",a[i]);
            Insert(a[i]);
        }
        bool flag = true;
        for(int i = 0; i < n; i++)
        {
            if(Find(a[i]) != 1)
            {
                flag = false;
                break;
            }
        }
        if(flag)puts("YES");
        else puts("NO");
        del(root);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/jifahu/p/5449417.html