HDU-1247 Hat's Words (字典树)


Hat’s Words

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 12123    Accepted Submission(s): 4329


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
 

Author
戴帽子的
 


字典树的具体用法可看:http://www.cnblogs.com/tanky_woo/archive/2010/09/24/1833717.html

贴个模板学习一下。

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
#define INF 0x3f3f3f3
const int N=50005;
const int mod=1e9+7;

typedef struct Trie{
    Trie *next[26];
    bool v;
}Trie;

Trie *root=(Trie *)malloc(sizeof(Trie));

void insert(char *str){
    int len=strlen(str);
    Trie *p = root,*q;
    for (int i=0; inext[id]==NULL) {
            q=(Trie *)malloc(sizeof(Trie));
            q->v=0;
            for (int j=0; j<26; j++)
                q->next[j]=NULL;
            p->next[id]=q;
        }
        p=p->next[id];
    }
    p->v=true;
}

int find(char *str){
    int len=strlen(str);
    Trie *p = root;
    for (int i=0; inext[id];
        if (p==NULL) return 0;
    }
    return p->v;
}

void del(Trie *root){
    for (int i=0; i<26; i++) {
        if (root->next[i]!=NULL) {
            del(root->next[i]);
        }
    }
    free(root);
}

char s[50005][50];

int main() {
    int count=0;
    char str[50];
    for (int i=0; i<26; i++) {
        root->next[i]=NULL;
    }
    root->v=0;
    while (scanf("%s",str)!=EOF) {
        strcpy(s[count++], str);
        insert(str);
    }
    for (int i=0; i

你可能感兴趣的:(字典(Trie)树,HDOJ)