Hat’s Words (字典树 + 智能指针shared_ptr)

来源:互联网 发布:域名购买是永久的吗 编辑:程序博客网 时间:2024/06/11 01:31

Hat’s Words

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 298 Accepted Submission(s): 138 
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 <stdio.h> #include <iostream> #include <algorithm> #include <cmath> #include <vector> #include <string.h> #include <memory> using namespace std; string sss[55]; struct Node {    int flag = 0;    shared_ptr<Node> next[50]; }; void insert(const shared_ptr<Node>& root, const string& str) {    shared_ptr<Node> cur(root);    int i = 0;    while (i < str.size()) {        int k = str[i] - 'a';        if (cur->next[k] == NULL) {        Node *p = new Node;        cur->next[k].reset(p);        cur = cur->next[k];        } else        cur = cur->next[k];        i++;    }    cur->flag = 1;} bool search(const shared_ptr<Node>& root,const string& str) {    shared_ptr<Node> cur(root);    for (int i = 0; i < str.size(); ++i) {        if (cur->next[str[i] - 'a'] == NULL)            return false;        cur = cur->next[str[i] - 'a'];    }    return cur->flag; }  int main() {    shared_ptr<Node> root(new Node);    int cnt = 0;    while (cin >> sss[cnt]) {        insert(root, sss[cnt++]);    }    for (int i = 0; i < cnt; ++i) {    int len = sss[i].size();    for (int j = 1; j < len - 1; ++j) {        string str1(sss[i], 0, j);        string str2(sss[i],j);        if (search(root, str1) && search(root, str2)){            cout << sss[i] << endl;            break;            }        }    } }


0 0