HDU 1247-Hat’s Words

来源:互联网 发布:淘宝卖家如何发布微淘 编辑:程序博客网 时间:2024/05/20 04:32

HDU 1247

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
a
ahat
hat
hatword
hziee
word

Sample Output
ahat
hatword

代码如下:

#include<stdio.h>#include<string.h>#include<stdlib.h>#define N 26char s[50005][100];struct node {    struct node *child[N];    int flag;};struct node *root;void inital(struct node *p) {    int i;    for(i=0;i<N;i++)     {        p->child[i]=NULL;    }    p->flag=0;    return;}void insert(char *str){    int i,len,k;    struct node *newnode,*current;    len=strlen(str);    current=root;    if(len==0) return ;    for(i=0;i<len;i++)     {        k=str[i]-'a';        if(current->child[k]!=NULL)            current=current->child[k];        else         {            newnode=(struct node *)malloc(sizeof(struct node));            inital(newnode);            current->child[k]=newnode;            current=newnode;        }    }    current->flag=1;}int find(char *str){    int len,i,k;    struct node *current;    current=root;    len=strlen(str);    for(i=0;i<len;i++)     {        k=str[i]-'a';        if(current->child[k]!=NULL)         {            current=current->child[k];        }        else             return 0;    }    return current->flag;}int main() {    int i,j,ans,n=0,len;    char s1[100],s2[100];    root=(struct node *)malloc(sizeof(struct node));    inital(root);    while(scanf("%s",s[n])!=EOF)    {         insert(s[n]);        n++;    }    for(i=0;i<n;i++)     {        len=strlen(s[i]);        for(j=1;j<=len-1;j++)         {            strncpy(s1,s[i],j);            s1[j]='\0';            strncpy(s2,s[i]+j,len-j);            s2[len-j]='\0';            ans=find(s1)+find(s2);            if(ans==2)            {                printf("%s\n",s[i]);                break;            }        }    }    return 0;    }
0 0
原创粉丝点击