uva 10391 Compound Words

来源:互联网 发布:c语言编写加法程序 编辑:程序博客网 时间:2024/06/05 01:10

原题:
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 <bits/stdc++.h>using namespace std;unordered_set<string> us;int main(){    ios::sync_with_stdio(false);    string s;    while(cin>>s)    {     //   if(s=="#")     //   break;        us.insert(s);    }    vector<string> vs(us.begin(),us.end());    vector<string> ans;    for(int i=0;i<vs.size();i++)    {        if(vs[i].size()==1)        continue;        for(int j=0;j<vs[i].size()-1;j++)        {           if(us.find(string(vs[i].begin(),vs[i].begin()+j+1))!=us.end()&&                      us.find(string(vs[i].begin()+j+1,vs[i].end()))!=us.end())            ans.push_back(vs[i]);        }    }    sort(ans.begin(),ans.end());    auto it=unique(ans.begin(),ans.end());    if(it!=ans.end())    ans.erase(it,ans.end());    for(auto ite=ans.begin();ite!=ans.end();ite++)    cout<<*ite<<endl;    return 0;}

解答:

题目很简单也很好理解,枚举两个单词,然后用set查找这个单词是否出现在这堆单词当中,结果超时了。当然,意料之中,因为单词的个数有120000个。改成用unordered_set后,还是超时-_- 后来想到可以分割单词,但是单词的长度题目中没给出,抱着试试看的心态,就过了。

0 0
原创粉丝点击