书山有径勤为路>>>>>>>>

<<<<<<<<学海无涯苦作舟!

Trie解决POJ 2503


题目:http://poj.org/problem?id=2503
就是一个字典树的简单应用, 不解释。 

View Code
#include "iostream"
using namespace std;

typedef struct node{
    char word[21];
    int mark;
    struct node * next[26];
}node;
node * root;
void InitRoot(){
    root = new node();
    root->mark=0;
    memset(root->next, NULL, sizeof(root->next));
}
void Build(char *key, char *val){
    node *p = root;
    int i, k, len = strlen(key);
    for(i=0; i<len; i++){
        k = key[i]-'a';
        if(p->next[k]==NULL){
            p->next[k] = new node();
            p->next[k]->mark = 0;
            strcpy(p->word, "");
            //注意下面一句是p->next[k]->next,不然读入时就会出错了
            memset(p->next[k]->next, NULL, sizeof(p->next[k]->next));
        }
        p = p->next[k];
        if(i==len-1){
            p->mark = 1;
            strcpy(p->word, val);
        }
    }
}
void Find(char *key){
    int i, j, k, len = strlen(key);
    node *p = root;
    for(i=0; i<len; i++){
        k = key[i]-'a';
        p = p->next[k];
        if(p==NULL){
            cout<<"eh"<<endl;
            break;
        }
        if(i==len-1){
            if(p->mark==1){
                cout<<p->word<<endl;
            }else{
                cout<<"eh"<<endl;
            }
        }
    }
}
int main(){
    char str[21], val[21], key[21];
    InitRoot();
    while(gets(str)&&str[0]){
        sscanf(str, "%s%s", val, key);
        Build(key, val);
    }
    while(scanf("%s", str)!=EOF){
        Find(str);
    }
    return 0;
}

 

 

posted on 2011-10-02 17:10  More study needed.  阅读(277)  评论(0编辑  收藏  举报

导航

书山有径勤为路>>>>>>>>

<<<<<<<<学海无涯苦作舟!