Advertisement
Guest User

Bonus

a guest
Oct 24th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.89 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3. struct spair
  4. {
  5.     int a, b, sum;
  6.     inline bool operator<(const spair& o) const
  7.     {
  8.         if (sum < o.sum) { return true; }
  9.         if (sum > o.sum) { return false; }
  10.         if (a < o.a) { return true; }
  11.         if (a > o.a) { return false; }
  12.         return b < o.b;
  13.     }
  14.     inline bool operator>(const spair& o) const { return !(operator<(o)); }
  15. };
  16. template<typename T>
  17. void fix_heap(T a[], int i, int n)
  18. {
  19.     int j = 2 * i + 1;
  20.     while (j < n)
  21.     {
  22.         if (j + 1 < n && a[j + 1] > a[j]) { j++; }
  23.         if (a[j] > a[i])
  24.         {
  25.             swap(a[j], a[i]);
  26.             i = j;
  27.             j = 2 * i + 1;
  28.         }
  29.         else { break; }
  30.     }
  31. }
  32. template<typename T>
  33. void construct_heap(T a[], int n)
  34. {
  35.     for (int i = (n - 2) / 2; i >= 0; i--) { fix_heap(a, i, n); }
  36. }
  37. template<typename T>
  38. void heap_sort(T a[], int n)
  39. {
  40.     construct_heap(a, n);
  41.     for (int i = n - 1; i > 0; i--)
  42.     {
  43.         swap(a[0], a[i]);
  44.         fix_heap(a, 0, i);
  45.     }
  46. }
  47. int find(spair a[], int n, int sum)
  48. {
  49.     int l = 0, r = n - 1, m;
  50.     while (l <= r)
  51.     {
  52.         m = (l + r) / 2;
  53.         if (a[m].sum < sum) {l = m + 1; }
  54.         else if (a[m].sum > sum) { r = m - 1; }
  55.         else { return m; }
  56.     }
  57.     return -1;
  58. }
  59. void solve(int a[], int as, int b[], int bs, int c[], int cs)
  60. {
  61.     spair* fs = new spair[bs * cs];
  62.     int fsi = 0;
  63.     for (int ai = 0; ai < as; ai++)
  64.     {
  65.         for (int bi = 0; bi < bs; bi++)
  66.         {
  67.             fs[fsi].a = a[ai];
  68.             fs[fsi].b = b[bi];
  69.             fs[fsi].sum = a[ai] + b[bi];
  70.             fsi++;
  71.         }
  72.     }
  73.     heap_sort(fs, fsi);
  74.     int idx = -1,ci = 0;
  75.     for (; ci < cs && idx != -1; ci++)
  76.     {
  77.         idx = find(fs, fsi, -c[ci]);
  78.     }
  79.     if (idx != -1)
  80.     {
  81.         ci--;
  82.         cout << "First number: " << fs[idx].a
  83.             << "\nSecond number: " << fs[idx].b
  84.             << "\nThird number: " << c[ci] << endl;
  85.     }
  86.     else
  87.     {
  88.         cout << "Didn't find any valid triple!" << endl;
  89.     }
  90.     delete[] fs;
  91. }
  92. int main()
  93. {
  94.     const int SZ = 5;
  95.     int a[SZ]{ 0,2,0,0,5 }, b[SZ]{ -6,8,0,7,6 }, c[SZ]{2,0,5,7,8};
  96.     solve(a, SZ, b, SZ, c, SZ);
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement