hdu 1247 Hat’s Words字典树

来源:互联网 发布:淘宝金冠店跑路 编辑:程序博客网 时间:2024/05/17 22:42

Problem Description
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
aahathathatwordhzieeword 

Sample Output
ahathatword题意是查找包含其他两个单词的单词,果断的字典树。AC代码:
#include<stdio.h>#include<stdlib.h>#include<string.h>#include<iostream>using namespace std;struct node{    struct node *child[26];           //指针数组    int cnt;                          //单词结束标志变量};struct node *root;void insert(char *s)               //建树函数{    struct node *now,*next;    now=root;    int len=strlen(s);    for(int i=0;i<len;i++)    {        next=now->child[s[i]-'a'];               if(!next)                            {            next=new node;            memset(next,0,sizeof(node));            now->child[s[i]-'a']=next;        }        now=next;    }    now->cnt=1;                      //单词结束标志}int find(char *s)                    //查找函数{    struct node *now,*next;    now=root;    int len=strlen(s);    for(int i=0;i<len;i++)    {        next=now->child[s[i]-'a'];        if(!next)            return 0;        now=next;    }    if(now->cnt==1)        return 1;    return 0;}char s[50005][105];int main(){    //freopen("in.txt","r",stdin);    root=new node;    memset(root,0,sizeof(node));    int n=0;    while(scanf("%s",s[n])!=EOF)    {        insert(s[n]);        n++;    }    char s1[105],s2[105],temp;    for(int i=0;i<n;i++)    {        for(int j=1;j<strlen(s[i]);j++)         //将一个单词分为拆为两部分        {            temp=s[i][j];            s[i][j]='\0';            strcpy(s1,s[i]);            s[i][j]=temp;            strcpy(s2,s[i]+j);            if(find(s1)&&find(s2))             //如果两部分都存在则输出            {                printf("%s\n",s[i]);                break;            }        }    }    return 0;}</span>


0 0
原创粉丝点击