1. 程式人生 > >【hdoj】1251 統計難題 【數據結構-Trie樹裸題】

【hdoj】1251 統計難題 【數據結構-Trie樹裸題】

lse show sin int 前綴 lock 參考 需要 hdu

傳送門:統計難題

題意:

字典樹裸題。

分析

字典樹板子,但是這題需要註意一點。
關於字典樹的只是可以參考hihocoder hiho一下 第二周

用G++提交會爆內存(Memory Limit Exceeded),用c++提交可以AC。

G++ 與 C++提交的區別

參考:OJ中的語言選項裏G++ 與 C++的區別

C++是一門計算機編程語言,而G++則是C++的編譯器。

選擇C++意味著你將使用C++最標準的編譯方式,也就是ANSI C++編譯。

選擇G++則意味這你使用GNU項目中適用人群最多的編譯器(其實也就是我們熟悉的Code::Blocks 自帶的編譯器)。

類似的還有選擇C和GCC,前者是標準的C編譯器,後者則是用GCC來編譯。

My AC Code

#include <iostream>
#include<cstdlib>
#include<cstring>

#define rep(i,a,b) for(int i=a;i<=b;i++)
using namespace std;
const int maxn=26;

struct TrieNode
{
    // 當前結點前綴的數量
    int prefix;
    TrieNode* Next[maxn];
};

typedef TrieNode Trie;

// 根不代表任何字母
void insert(Trie *root,char *s)
{
    Trie*  p=root;  
    while(*s!=‘\0‘)
    {
        if(p->Next[*s-‘a‘]==NULL)
        {
            Trie* temp=new Trie();
            for(int i=0;i<maxn;i++)
            {
                temp->Next[i]=NULL;
            }
            temp->prefix=1;
            p->Next[*s-‘a‘]=temp;
            p=p->Next[*s-‘a‘];
        }
        else
        {           
            p=p->Next[*s-‘a‘];
            p->prefix++;
        }
        s++;
    }
}

int count(Trie *root,char *pre)
{
    Trie* p=root;
    while(*pre!=‘\0‘)
    {
        if(p->Next[*pre-‘a‘]==NULL)
            return 0;
        else
        {
            p=p->Next[*pre-‘a‘];
            pre++;
        }
    }
    return p->prefix;
}

void del(Trie *root)
{
    for(int i=0;i<maxn;i++)
    {
        if(root->Next[i]!=NULL)
            del(root->Next[i]);
    }
    free(root);
}

int main()
{
    char s[16];
    Trie *root=new Trie();
    for(int i=0;i<maxn;i++)
        root->Next[i]=NULL;
    root->prefix=0;
    while(1)
    {
        gets(s);
        if(strcmp(s,"")==0)
        {
            break;
        }
        insert(root,s);
    }
    while(gets(s))
    {
        printf("%d\n",count(root,s));
    }
    del(root);
    return 0;
}

【hdoj】1251 統計難題 【數據結構-Trie樹裸題】