uva-10391 Compound Words

题目

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

分析

  一开始的思路是既然是两个词的合成,对于某个词,肯定有另外一个词是它的前缀,而所给的单词序列又是排好序的,既然如此,直接从这个单词往前缀,如果能找到就直接找二分查找剩下的字母是否能在单词序列里找到,如果不是前缀那么前边一定也没有这个单词的前缀了(就是这里思路出问题了,比如序列a, abc, abde这就不符合我的思路,原来的想法有点想当然了)。gg之后重写,暴力拆分所有单词然后分别二分查找,ac,暴力大法好啊!

ac代码

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
vector   str;
bool binary_search(const string &s){
    int l = 0, r = str.size();
    while(l != r){
        int mid = (l + r) / 2;
        if(str[mid] == s) return 1;
        else if(str[mid] > s) r = mid;
        else l = mid + 1;
    }
    return 0;
}
int main(){
    string temp;
    while(cin >> temp){
        str.push_back(temp);
    }
    for(int i = 0; i < str.size(); ++i){
        if(str[i].size() >= 2){
            for(int j = 1; j < str[i].size() - 1; ++j){
                if(binary_search(string(str[i], 0, j)) && binary_search(string(str[i], j))){
                    cout << str[i] << endl;
                    break;
                }
            }
        }
    }
    return 0;
} 

你可能感兴趣的:(uva-10391 Compound Words)