UVA-10391 二分

来源:互联网 发布:流程图绘制软件 编辑:程序博客网 时间:2024/06/07 07:38

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;  }  
原创粉丝点击