hdu 1247 字典树

A hat’s word is a word in the dictionary that is the concatenation of exactly two other words in the dictionary.
You are to find all the hat’s words in a dictionary.
Input
Standard input consists of a number of lowercase words, one per line, in alphabetical order. There will be no more than 50,000 words.
Only one case.
Output
Your output should contain all the hat’s words, one per line, in alphabetical order.
Sample Input
a
ahat
hat
hatword
hziee
word
Sample Output
ahat
hatword

题解:如果一个单词是由出现过的两个单词组成,那么便是hat’s word

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;
const int maxn=50010;
int vis[maxn];
char s1[50],s2[50];
struct tree {
    tree *child[26];
    int flag;
    tree() {
        flag=0;
        memset(child,0,sizeof(child));
    }
};
tree *root;
char str[maxn][26];
void insert(char *source) {
    tree *cur,*tmp;
    int len=strlen(source);
    cur=root;
    for(int i=0; iif(cur->child[source[i]-'a']!=0)
            cur=cur->child[source[i]-'a'];
        else {
            tmp=new tree;
            cur->child[source[i]-'a']=tmp;
            cur=tmp;
        }
    }
    cur->flag=1;
}
int find(char *source) {
    tree *cur;
    int len=strlen(source);
    cur=root;
    for(int i=0; iif(cur->child[source[i]-'a']!=0)
            cur=cur->child[source[i]-'a'];
        else return 0;
    }
    return cur->flag;
}
int main() {
//  freopen("input.txt","r",stdin);
    root=new tree;
    int k=0;
    while(scanf("%s",str[k])!=EOF) {
        insert(str[k]);
        k++;
    }
    for(int i=0; iint len=strlen(str[i]);
        vis[i]=0;
        if(len==1)  continue;
        for(int x=1; xint j,j2;
            for(j=0; j'\0';
            for(j2=0; j'\0';
            if(find(s1)&&find(s2))  {
                vis[i]=1;
                break;
            }
        }
    }
    for(int i=0; iif(vis[i])
            printf("%s\n",str[i]);
    return 0;
}

你可能感兴趣的:(线段树)