字典树

来源:互联网 发布:小额贷款哪个软件最好 编辑:程序博客网 时间:2024/05/16 01:54

Hat’s Words

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 293 Accepted Submission(s): 136 
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
#include <iostream>#include <sstream>#include <string.h>#include <cstdio>#include <string>#include <cctype>#include <algorithm>#include <vector>#include <stack>#include <queue>#include <set>#include <cmath>#define PI acos(-1)#define ll long long#define INF 0x7fffffff#define _N 50005using namespace std;char word[_N][30];struct Node {    bool is;    Node *next[30];    Node() {        is = false;        memset(next, 0, sizeof(next));    }};/// create treevoid insert(Node *root, char *s){    Node *p = root;    int i = 0;    while (s[i]) {        int j = s[i++] - 'a';        if (p->next[j] == NULL) {            p->next[j] = new Node();        }        p = p->next[j];    }    p->is = true;}int search(Node *root, char *s) {    // printf("%s\n", s);    int i = 0;    int top = 0;    int stack[1005];    Node *p = root;    while (s[i]) {        int j = s[i++] - 'a';        if (p->next[j] == NULL) return 0;        p = p->next[j];        /// save        if (p->is && s[i])            stack[top++] = i;    }    while (top) {        int flag = 1;        i = stack[--top];        p = root;        while (s[i]) {            int j = s[i++] - 'a';            if (p->next[j] == NULL) {                flag = 0;                break;            }            p = p->next[j];        }        if (flag && p->is) return 1;    }    return 0;}int main() {    // freopen("in.txt", "r", stdin);    int i = 0;    Node *root = new Node();    while (~scanf("%s", word[i])) {        insert(root, word[i]);        i++;    }    for (int j = 0; j < i; j++) {        // printf("%s", word[j]);        if (search(root, word[j])) {            printf("%s\n", word[j]);        }    }    return 0;}


0 0