Use this to learn the idea, then write your own version.
1class SegmentTree {2 public:3 explicit SegmentTree(const vector<int>& nums)4 : maxNum(nums.size()), nums(std::move(nums)), tree(4 * maxNum, -1) {}5 6 7 8 9 void update(int i, int numIndex) {10 update(0, 0, maxNum, i, numIndex);11 }12 13 14 int query(int i, int j) const {15 return query(0, 0, maxNum, i, j);16 }17 18 private:19 20 static constexpr int kDefaultValue = -1;21 const int maxNum;22 const vector<int> nums; 23 vector<int> tree; 24 25 void update(int treeIndex, int lo, int hi, int i, int numIndex) {26 if (lo == hi) {27 tree[treeIndex] = merge(tree[treeIndex], numIndex);28 return;29 }30 const int mid = (lo + hi) / 2;31 if (i <= mid)32 update(2 * treeIndex + 1, lo, mid, i, numIndex);33 else34 update(2 * treeIndex + 2, mid + 1, hi, i, numIndex);35 tree[treeIndex] = merge(tree[2 * treeIndex + 1], tree[2 * treeIndex + 2]);36 }37 38 int query(int treeIndex, int lo, int hi, int i, int j) const {39 if (i <= lo && hi <= j) 40 return tree[treeIndex];41 if (j < lo || hi < i) 42 return kDefaultValue;43 const int mid = (lo + hi) / 2;44 return merge(query(2 * treeIndex + 1, lo, mid, i, j),45 query(2 * treeIndex + 2, mid + 1, hi, i, j));46 }47 48 49 50 int merge(const int& i, const int& j) const {51 if (i == -1)52 return j;53 if (j == -1)54 return i;55 if (nums[i] > nums[j])56 return i;57 if (nums[j] > nums[i])58 return j;59 return min(i, j);60 }61};62 63class Solution {64 public:65 vector<int> beautifulPair(vector<int>& nums1, vector<int>& nums2) {66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 constexpr int kInf = 1'000'000'000;84 const int n = nums1.size();85 vector<int> ans(2, n);86 vector<int> nums2PlusNums1;87 vector<int> nums2MinusNums1;88 vector<int> indices;89 int minBeauty = INT_MAX;90 91 for (int i = 0; i < n; ++i) {92 nums2PlusNums1.push_back(nums2[i] + nums1[i]);93 nums2MinusNums1.push_back(nums2[i] - nums1[i]);94 indices.push_back(i);95 }96 97 ranges::sort(indices,98 [&nums2](int i, int j) { return nums2[i] < nums2[j]; });99 100 SegmentTree tree1(nums2PlusNums1);101 SegmentTree tree2(nums2MinusNums1);102 103 for (const int i : indices) {104 const int num = nums1[i];105 106 107 int j = tree1.query(0, num);108 if (j >= 0)109 updateAns(nums2PlusNums1, i, j, minBeauty, ans);110 tree1.update(num, i);111 112 113 j = tree2.query(num, n);114 if (j >= 0)115 updateAns(nums2MinusNums1, i, j, minBeauty, ans);116 tree2.update(num, i);117 }118 119 return ans;120 }121 122 private:123 void updateAns(const vector<int>& nums, int i, int j, int& minBeauty,124 vector<int>& ans) {125 126 const int beauty = nums[i] - nums[j];127 const vector<int> nextAns = {min(i, j), max(i, j)};128 if (beauty < minBeauty) {129 minBeauty = beauty;130 ans = nextAns;131 } else if (beauty == minBeauty) {132 ans = min(ans, nextAns);133 }134 }135};136