fork download
  1. #include <iostream>
  2. #include <queue>
  3. #include <cstring>
  4. #include <algorithm>
  5. #include <iterator>
  6. struct strptr;
  7. typedef std::priority_queue<strptr> pqueue;
  8. void put_words(pqueue& pq, const char* s, const char* delim);
  9. bool out_share_words(std::ostream& _out, pqueue& pq1, pqueue& pq2);
  10.  
  11. struct strptr {
  12. const char* ptr;
  13. int len;
  14.  
  15. strptr(void):ptr(NULL), len(0){}
  16. strptr(const char* _p, int _n):ptr(_p), len(_n){}
  17.  
  18. bool operator < (const strptr& p) const {
  19. return ((len < p.len) ||
  20. ((len == p.len) && std::lexicographical_compare(p.ptr, p.end(), ptr, ptr + len)));
  21. }
  22.  
  23. const char* begin(void) const { return ptr; }
  24. const char* end(void) const { return ptr + len; }
  25. };
  26.  
  27.  
  28. int main(void){
  29. char s1[] = "AAAA, BBBB, XXXX, ABCD, D, EEEE, F...QQQQ";
  30. char s2[] = "EEEE, QQQQ, Z, X, YY. ABCD, AAAA";
  31.  
  32. pqueue pq1, pq2;
  33. put_words(pq1, s1, " \n\t.,");
  34. put_words(pq2, s2, " \n\t.,");
  35.  
  36. if(! out_share_words(std::cout, pq1, pq2))
  37. std::cout << "Not find!" << std::endl;
  38. return 0;
  39. }
  40.  
  41. //вывод самых длинных общих слов
  42. bool out_share_words(std::ostream& _out, pqueue& pq1, pqueue& pq2){
  43. std::ostream_iterator<char> _osrt(_out, "");
  44. if(pq1.empty() || pq2.empty())
  45. return false;
  46.  
  47. int n = pq1.top().len;
  48. if(n != pq2.top().len)
  49. return false;
  50.  
  51. bool ok = false;
  52. while(!pq1.empty() && !pq2.empty()){
  53. if((pq1.top().len != n) || (pq2.top().len != n))
  54. break;
  55.  
  56. const strptr& a = pq1.top();
  57. const strptr& b = pq2.top();
  58. if(std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end()))
  59. pq1.pop();
  60. else {
  61. if(! memcmp(a.begin(), b.begin(), b.len)){
  62. std::copy(a.begin(), a.end(), _osrt);
  63. std::cout << std::endl;
  64. ok = true;
  65. pq1.pop();
  66. }
  67. pq2.pop();
  68. }
  69. }
  70. return ok;
  71. }
  72.  
  73. //слова
  74. void put_words(pqueue& pq, const char* s, const char* delim){
  75. int n, m = 0;
  76. const char* p = s;
  77. while((s = strpbrk(s, delim)) != NULL){
  78. n = (int)(s - p);
  79. if((n > 0) && (n >= m)){
  80. m = n;
  81. pq.push(strptr(p, n));
  82. }
  83.  
  84. while(*s && (strchr(delim, *s) != NULL))
  85. ++s;
  86. p = s;
  87. }
  88.  
  89. if(*p){
  90. for(s = p; *s; ++s)
  91. ;
  92. if(((n = (int)(s - p)) > 0) && (n >= m))
  93. pq.push(strptr(p, n));
  94. }
  95. }
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
AAAA
ABCD
EEEE
QQQQ