hdu1247 Hat’s Words

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

Sample Output
ahat hatword
 
题意:给你多个字符串,找出能切成两个当中字符串拼接起来的字符串,然后按字典序输出。
思路:可以建一棵字典树,当一个字符串,如果发现插入过程中的中间有节点是之前节点的尾节点,那么就去查询剩下的部分,看有没有在字典树中,如果有,那么这个就符合条件。

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<string>
#include<algorithm>
using namespace std;
typedef long long ll;
#define inf 99999999
#define pi acos(-1.0)
#define maxnode 10000000
int sz,tot;
int ch[maxnode][30];
int val[maxnode];
struct node{
    char s[1000];
    int len;
}a[50005],b[50005];
bool cmp1(node a,node b){
    return a.len<b.len;
}
bool cmp2(node a,node b){
    return strcmp(a.s,b.s)<0;
}



void init()
{
    sz=0;
    memset(ch[0],0,sizeof(ch[0]));
}
int idx(char c){
    return c-'a';
}
int flag;
int chazhao(char *s)
{
    int i,u=0;
    int len=strlen(s);
    for(i=0;i<len;i++){
        int c=idx(s[i]);
        if(!ch[u][c]){
            return 0;
        }
        else{
            u=ch[u][c];
        }
    }
    if(val[u])return 1;
    return 0;



}


void charu(char *s){
    int i,u=0,j;
    int len=strlen(s);
    char s1[1000];
    for(i=0;i<len;i++){
        int c=idx(s[i]);
        if(!ch[u][c]){
            sz++;
            ch[u][c]=sz;
            val[sz]=0;
            u=sz;
        }
        else if(ch[u][c]){
            if(val[ch[u][c] ]  && (i != len-1) ){
                memset(s1,0,sizeof(s1));
                for(j=i+1;j<len;j++){
                    s1[j-i-1]=s[j];
                }
                s1[len-i-1]='\0';
                if(chazhao(s1))flag=1;
            }
            u=ch[u][c];
        }
    }
    val[u]=1;
}




int main()
{
    int n,m,i,j;
    init();
    tot=0;
    while(scanf("%s",a[++tot].s)!=EOF)
    {
        a[tot].len=strlen(a[tot].s);
    }
    sort(a+1,a+1+tot,cmp1);

    int cnt=0;
    for(i=1;i<=tot;i++){
        flag=0;
        charu(a[i].s);
        if(flag){
            cnt++;
            strcpy(b[cnt].s,a[i].s);
        }
    }
    sort(b+1,b+1+cnt,cmp2);
    for(i=1;i<=cnt;i++){
        printf("%s\n",b[i].s);
    }
}


/*
abcd
ab
abcdab
ababcd
efg
abefg
efgabcd
*/



posted @ 2016-02-05 13:37  Herumw  阅读(119)  评论(0编辑  收藏  举报