hdu_1671 - 字典树

来源:互联网 发布:apache centos e325 编辑:程序博客网 时间:2024/06/06 12:25

一道非常简单的字典树,一开始没有写析构函数,结果居然超内存了!!!悲剧。。。

话说哥的写法还是很标准的~~

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
const int ax='0';
struct tree
{
    bool has;
    tree *p[10];
    tree()
    {
        for(int i=0;i<10;i++)
        {
            p[i]=NULL;
        }
        has=false;
    }
    ~tree()
    {
        for(int i=0;i<10;i++)       
        {       
            if(p[i]!=NULL)
            {
                delete p[i];
            }
        }
    }
}*head,*now;
int T,w;
string a,b,c;
vector<string>vs;
bool insert(string x)
{
    for(int i=0;i<x.length();i++)
    {
        if(i==0)
        {
            if(head->p[x[i]-ax]==NULL)      
            {
                head->p[x[i]-ax]=new tree;
                now=head->p[x[i]-ax];
            }
            else
            {
                now=head->p[x[i]-ax];
                if(now->has==true)
                {
                    return false;
                }
            }
        }  
        else
        {
            if(now->p[x[i]-ax]==NULL)
            {
                now->p[x[i]-ax]=new tree;    
                now=now->p[x[i]-ax];
            }
            else
            {   
                now=now->p[x[i]-ax];
                if(now->has==true)
                {
                    return false;
                }
            }
        }
    }  
    
    for(int i=0;i<10;i++)
    {
        if(now->p[i]!=NULL)
        {
            return false;
        }
    }
    now->has=true; 
    return true;
}
bool fuck()
{
    for(int i=0;i<vs.size();i++)
    {
        if(!insert(vs[i]))
        {
            return false;       
        }
    }    
    return true;
}
int main()      
{
    cin>>T;
    for(int tt=1;tt<=T;tt++)
    {
        cin>>w;
        vs.clear();
        head=new tree;
        for(int i=1;i<=w;i++)
        {       
            cin>>a; 
            vs.push_back(a);
        }    
        if(fuck())      
        {
            cout<<"YES"<<endl;
        }
        else
        {
            cout<<"NO"<<endl;
        }
        delete head;
    }       
    return 0;
}


原创粉丝点击