复合词 UVa-10391

--write by zhuwx 2019-06-24 20:57:48 +0800 CST

点击量:35

You are to find all the two-word compound words in a dictionary. A two-word compound word is a word in the dictionary that is the concatenation of exactly two other words in the dictionary.
Input
Standard input consists of a number of lowercase words, one per line, in alphabetical order. There will be no more than 120,000 words.
Output
Your output should contain all the compound words, one per line, in alphabetical order.
Sample Input
a alien born less lien never nevertheless new newborn the zebra
Sample Output
alien newborn

#include<iostream>
#include<string>
#include<set>
#include<map>
#include<algorithm>
using namespace std;

const int maxn = 120010;
string words[maxn];
map<string, bool>myhash;
set<string>ans;

int main()
{
    int cnt = 0;
    while (cin >> words[cnt])
    {
        myhash[words[cnt++]] = true;
    }
    for (int i = 0; i < cnt; i++)
    {
        for (int j = 0; j < int (words[i].size() - 1); j++)
        {
            string a = words[i].substr(0, j + 1);
            string b = words[i].substr(j + 1);
            if (myhash[a] && myhash[b])
            {
                ans.insert(words[i]);    //可能出现重复的情况
            }
        }
    }
    for (set<string>::iterator it = ans.begin(); it != ans.end(); it++)
        cout << *it;
    return 0;
}