Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- struct spair
- {
- int a, b, sum;
- inline bool operator<(const spair& o) const
- {
- if (sum < o.sum) { return true; }
- if (sum > o.sum) { return false; }
- if (a < o.a) { return true; }
- if (a > o.a) { return false; }
- return b < o.b;
- }
- inline bool operator>(const spair& o) const { return !(operator<(o)); }
- };
- template<typename T>
- void fix_heap(T a[], int i, int n)
- {
- int j = 2 * i + 1;
- while (j < n)
- {
- if (j + 1 < n && a[j + 1] > a[j]) { j++; }
- if (a[j] > a[i])
- {
- swap(a[j], a[i]);
- i = j;
- j = 2 * i + 1;
- }
- else { break; }
- }
- }
- template<typename T>
- void construct_heap(T a[], int n)
- {
- for (int i = (n - 2) / 2; i >= 0; i--) { fix_heap(a, i, n); }
- }
- template<typename T>
- void heap_sort(T a[], int n)
- {
- construct_heap(a, n);
- for (int i = n - 1; i > 0; i--)
- {
- swap(a[0], a[i]);
- fix_heap(a, 0, i);
- }
- }
- int find(spair a[], int n, int sum)
- {
- int l = 0, r = n - 1, m;
- while (l <= r)
- {
- m = (l + r) / 2;
- if (a[m].sum < sum) {l = m + 1; }
- else if (a[m].sum > sum) { r = m - 1; }
- else { return m; }
- }
- return -1;
- }
- void solve(int a[], int as, int b[], int bs, int c[], int cs)
- {
- spair* fs = new spair[bs * cs];
- int fsi = 0;
- for (int ai = 0; ai < as; ai++)
- {
- for (int bi = 0; bi < bs; bi++)
- {
- fs[fsi].a = a[ai];
- fs[fsi].b = b[bi];
- fs[fsi].sum = a[ai] + b[bi];
- fsi++;
- }
- }
- heap_sort(fs, fsi);
- int idx = -1,ci = 0;
- for (; ci < cs && idx != -1; ci++)
- {
- idx = find(fs, fsi, -c[ci]);
- }
- if (idx != -1)
- {
- ci--;
- cout << "First number: " << fs[idx].a
- << "\nSecond number: " << fs[idx].b
- << "\nThird number: " << c[ci] << endl;
- }
- else
- {
- cout << "Didn't find any valid triple!" << endl;
- }
- delete[] fs;
- }
- int main()
- {
- const int SZ = 5;
- int a[SZ]{ 0,2,0,0,5 }, b[SZ]{ -6,8,0,7,6 }, c[SZ]{2,0,5,7,8};
- solve(a, SZ, b, SZ, c, SZ);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement