hdu 1251 统计难题

汉语提,题意清楚。当初还卡了我一个上午。哎。

ac代码:

View Code
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <string>
#include <set>

using namespace std;

const int maxn=26;

struct node
{
    int cnt;
    node *next[maxn];
    node()
    {
        cnt=0;
        for(int i=0;i<maxn;i++)
            next[i]=NULL;
    }
    ~node()
    {
        for(int i=0;i<maxn;i++)
            if(next[i]!=NULL) delete next[i];
    }
};

class Trie
{
    public:
    node *root;
    Trie()
    {
        root=NULL;
    }
    void Insert(string str)
    {
        if(!root)
            root=new node();
        node *location=root;
        for(int i=0;i<str.length();i++)
        {
            int num=str[i]-'a';
            if(location->next[num]==NULL)
                location->next[num]=new node();
            location->next[num]->cnt++;
            location=location->next[num];
        }
    }
    int Search(string str)
    {
        node *location=root;
        for(int i=0;i<str.length();i++)
        {
            int num=str[i]-'a';
            if(location->next[num]==NULL)
                return 0;
            location=location->next[num];
        }
        return location->cnt;
    }
}t;

int main()
{
    char ss[20];
    string str;
    while(cin.getline(ss,20) )
    {
        str = ss;
        if(str== "") break;
//        for(int i = 0 ;i < strlen(ss); i ++) str += ss[i];
//        cout << "str == " << str  << endl;
        t.Insert(str);
//        getchar();
//        ch = getchar();
    }
    while(cin.getline(ss,20))
    {
//        cout << "fff " << str << endl;
        str=ss;
        cout<<t.Search(str)<<endl;
    }
    return 0;
}

欢迎批评指正。谢谢!

posted on 2012-11-12 16:44  Raining Days  阅读(157)  评论(0编辑  收藏  举报

导航