HDU1247(字典树)

Hat’s Words

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

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

用STL也可以写,练习字典树,就写了字典树。

#include <iostream>
#include <string> 
#include <cstring>
#include <vector>
#include<malloc.h>
using namespace std;
vector<string>s;
struct node
{
    bool flag;
    struct node *next[26];
};

node root;

void Insert(string str)
{
    node *p;
    p = root;
    int len = str.size();
    for(int i = 0; i < len; i ++)
    {
        if(p -> next[str[i] - 'a'] == NULL)
            p -> next[str[i] - 'a'] = new node();
        p = p -> next[str[i] - 'a'];
    }
    p -> flag = true;
}
int query(string str)
{
    node *p;
    p = root;
    int len = str.size();
    for(int i = 0; i < len; i ++)
    {
        if(p -> next[str[i]- 'a'] == NULL)
            return 0;
        p = p -> next[str[i] - 'a'];
    }
    if(p -> flag) return 1;
    else return 0;
}
 
int main()
{
    root =new node();
    string str,str1,str2;
    while(cin>>str)
    {
    	s.push_back(str);
        Insert(str);
    }
    for(int i = 0; i < s.size(); i ++)
    {
    	str=s[i];
        int len = str.size();
        for(int j = 0; j < len; j ++)
        {
            str1=str.substr(0,j);
            str2=str.substr(j,len-j);
            if(query(str1) && query(str2))
            {
                cout<<str<<endl;
                break;
            }
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/love20165104027/article/details/81805523