poj2001 字典树

来源:互联网 发布:北京赛车pk10微信源码 编辑:程序博客网 时间:2024/06/06 14:00
/** * poj2001 字典树trie * 知道是使用字典树就可以了,要注意树的树根是一个二级指针,因此结构体内也要使用指针数组 * 在字典树的结构体内,既维护树形的结构,也使用一个变量标记以当前(从上往下)为前缀的单词的个数 * 在最后检验时,自上而下查询一个词,并输出当前的前缀,直到向下的统计量为1,停止输出即可 */#include <cstdio>#include <iostream>#include <cstdlib>#include <cstring>using namespace std;const int MAX_NUM = 1001;const int MAX_LEN = 21;char ss[MAX_NUM][MAX_LEN];struct node{    int count;    node *next[26];    node(){        count=0;        for(int i=0;i<26;++i){            next[i] = NULL;        }    }} *root;void addword(char *s){    node *r = root;    int i;    for(i=0;i<strlen(s);++i){        if(r->next[s[i]-'a'] == NULL){            r->next[s[i]-'a'] = new node;        }        r = r->next[s[i]-'a'];        ++(r->count);    }}void checkword(char *s){    node *r = root;    int i;    for(i=0;i<strlen(s);++i){        r = r->next[s[i]-'a'];        printf("%c",s[i]);        if(r->count <= 1){            break;        }    }    printf("\n");}int main(){    int scount = 0;    root = new node;    while(scanf("%s",ss[scount]) != EOF){        addword(ss[scount]);        ++scount;    }    ++scount;    for(int i=0;i<scount;++i){        printf("%s ",ss[i]);        checkword(ss[i]);    }    return 0;}

0 0
原创粉丝点击