hdu 1247 字典树

来源:互联网 发布:优酷淘宝搞笑视频 编辑:程序博客网 时间:2024/06/05 13:50

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 <iostream>#include <cstdio>#include <algorithm>#include <cstring>#include <string>#include <cmath>#include <queue>#include <vector>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; i<len; i++) {        if(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; i<len; i++) {        if(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; i<k; i++) {        int len=strlen(str[i]);        vis[i]=0;        if(len==1)  continue;        for(int x=1; x<len; x++) {            int j,j2;            for(j=0; j<x; j++)                s1[j]=str[i][j];            s1[j]='\0';            for(j2=0; j<len; j++,j2++)                s2[j2]=str[i][j];            s2[j2]='\0';            if(find(s1)&&find(s2))  {                vis[i]=1;                break;            }        }    }    for(int i=0; i<k; i++)        if(vis[i])            printf("%s\n",str[i]);    return 0;}
原创粉丝点击