Problem E: 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
题意:给出一系列单词,找出由其中两个单词复合组成的单词。直接排序然后二分查找了。
#include<iostream> #include<string> #include<algorithm> using namespace std; int k; string st[120005]; bool cmp(string x,string y) { return x<y; } int search(string str) { int left=0,right=k-1,mid; while(left<=right) { mid=(left+right)/2; if(st[mid]<str) { left=mid+1; } else if(st[mid]>str) { right=mid-1; } else return 1; } return 0; } int main() { string str; int i,j; k=0; while(getline(cin,str)) { st[k++]=str; } sort(st,st+k,cmp); //cout<<k<<endl; for(i=0;i<k;i++) { for(j=1;j<st[i].size()-1;j++) { string str1(st[i],0,j); string str2(st[i],j,(st[i].size()-j)); if(search(str1)&&search(str2)) { cout<<st[i]<<endl; break; } } } return 0; }