1. 程式人生 > >紫書第五章訓練2 F - Compound Words

紫書第五章訓練2 F - Compound Words

每次 bre main sed color ons div img insert

F - 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

這個題就是找個單詞是已出現兩個單詞的和,我用map寫一直錯, 我分析了下大概是每次都要訪問map,然後map的空間就不夠了,所以還是用set搞下不錯,他和map的查詢復雜度都是logn的,運用string還有find豈不是很簡單實用,美滋滋

不過需要提出的是字典樹或者直接數組搞會比stl速度快些的

技術分享
#include <bits/stdc++.h>
using namespace std;
int main(){
string s;
set<string>ma;
while(cin>>s){
    ma.insert(s);
}
set<string>::iterator it;
for(it=ma.begin();it!=ma.end();it++){
    string c=*it;
    for(int i=1;c[i];i++){
        if(ma.find(c.substr(0
,i))!=ma.end()&&ma.find(c.substr(i))!=ma.end()){ cout<<c<<endl; break; } } } return 0;}
View Code

紫書第五章訓練2 F - Compound Words