POJ 3283 典型的字典树trie tree 问题

本题是要实现一个倒置的字典树,此处用map来存储键值key以及所对应的权值value,方便搜索;

本题有一个需要注意的地方;由于要从后开始向前来建立字典树,尽量使用 栈 stack 来存储 key 值;

而不要获取长串在解析串,解析的时候很难解析对,因为里边 或是夹杂多个“空格”,获取其他的字符,

考虑不全不可能解出本题,所以要避免;

代码如下:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <map>
#include <stack>
#include <memory.h>
using namespace std;
#define N 100010

std::map<string,int> HASH;
std::stack<string> sta;
string card;
int cs,num,i,k,len,pos;
int idn;    //标志当前节点的个数

struct node
{
    struct node * next[53];
    void init()
    {
        for( i=0 ;i<53;i++)
            next[i] = NULL;
    }
} *root;

void inithash()
{
    HASH["AC"] = 0; HASH["2C"] = 1; HASH["3C"] = 2; HASH["4C"] = 3;
    HASH["5C"] = 4; HASH["6C"] = 5; HASH["7C"] = 6; HASH["8C"] = 7;
    HASH["9C"] = 8; HASH["10C"] = 9; HASH["JC"] = 10; HASH["QC"] = 11;
    HASH["KC"] = 12; HASH["AD"] = 13; HASH["2D"] = 14; HASH["3D"] = 15;
    HASH["4D"] = 16; HASH["5D"] = 17; HASH["6D"] = 18; HASH["7D"] = 19;
    HASH["8D"] = 20; HASH["9D"] = 21; HASH["10D"] = 22; HASH["JD"] = 23;
    HASH["QD"] = 24; HASH["KD"] = 25; HASH["AH"] = 26; HASH["2H"] = 27;
    HASH["3H"] = 28; HASH["4H"] = 29; HASH["5H"] = 30; HASH["6H"] = 31;
    HASH["7H"] = 32; HASH["8H"] = 33; HASH["9H"] = 34; HASH["10H"] = 35;
    HASH["JH"] = 36; HASH["QH"] = 37; HASH["KH"] = 38; HASH["AS"] = 39;
    HASH["2S"] = 40; HASH["3S"] = 41; HASH["4S"] = 42; HASH["5S"] = 43;
    HASH["6S"] = 44; HASH["7S"] = 45; HASH["8S"] = 46; HASH["9S"] = 47;
    HASH["10S"] = 48; HASH["JS"] = 49; HASH["QS"] = 50; HASH["KS"] = 51;
}

void build( )
{
    struct node * temp = root;
    int curid;

    while( !sta.empty() )
    {
        card = sta.top();
        sta.pop();
        curid = HASH[card];

        if( temp->next[curid] != NULL)
            temp = temp->next[curid];
        else
        {
            temp->next[curid] = new struct node;
            temp = temp->next[curid];
            temp->init();
            idn++;
        }
    }
}
void del( struct node * temp)
{
    if(temp == NULL)
        return;
    for( i=0;i<53;i++)
    {
        if(temp->next[i])
            del(temp->next[i]);
    }
    delete temp;
    temp = NULL;
    return;
}
int main()
{
    inithash();
    while(cin>>cs && cs)
    {
        root = new struct node;
        root->init();
        idn = 0;
        while( !sta.empty() )
            sta.pop();
        for( k=1 ;k <= cs ;k++)
        {
            cin>>num;
            int j;
            for(j=1;j<=num;j++)
            {
                cin>>card;
                sta.push(card);
            }
            build();
        }
        cout<<idn<<endl;
        del(root);
    }
    return 0;
}


 

你可能感兴趣的:(struct,tree,null,delete,存储,Build)