【字典树】HDU1247Hat’s Words

来源:互联网 发布:比价商城源码 编辑:程序博客网 时间:2024/05/19 04:02

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1247

#include<iostream>#include<string>#include<cstdio>#include<cstring>using namespace std;const int N=26;char s[50005][50];struct node {    bool flag;    node *next[N];    node(){        flag=false;        memset(next,0,sizeof(next));    }};node *p,*head=new node();void Insert(char s[])           //  建立字典树;{    p=head;    int i=0;    while(s[i]){        int id=s[i++]-'a';        if(p->next[id]==NULL) p->next[id]=new node();        p=p->next[id];    }    p->flag=true;               //  标记一个单词的结尾;}bool Query(char s[]){    p=head;    int i=0,top=0,Stack[1005];    while(s[i]){        int id=s[i++]-'a';        if(p->next[id]==NULL) return false;     //  说明该单词不可拆分为两个单词;        p=p->next[id];        if(p->flag&&s[i]) Stack[top++]=i;       //  该单词可以拆分的第一个单词结尾;    }    while(top){         //  遍历可拆分的每一个单词的结尾;        i=Stack[--top];        p=head;        bool ok=true;        while(s[i]){            int id=s[i++]-'a';            if(p->next[id]==NULL){                ok=false;                break;            }            p=p->next[id];        }        if(ok&&p->flag) return true;        //  刚刚完全遍历这个单词;    }    return false;}int main(){    int k=0;    while(gets(s[k])) Insert(s[k++]);    for(int i=0;i<k;i++){        if(Query(s[i]))            printf("%s\n",s[i]);    }    return 0;}


0 0
原创粉丝点击