Domanda

c8d6743b-842f-44ef-8ae2-c2ebf00074f1.jpg
893bc2d3-eb68-47be-9f5c-f809339cc1b0.jpg
33c004da-396f-43d0-aaea-1ea4176d0b9d.jpg
90fe3c22-57d1-4487-825c-19c9e90c79fa.jpg
f63c6192-c2df-411f-95e9-54d130575e6e.jpg
6e1885ef-6c1a-48ac-8f81-8e397e536ea0.jpg

in c++

Pensiero

Breaking down problem for C++ solution

The task is to efficiently solve a problem based on screenshots. I need to handle constraints—n, m up to 2e5 and arr[i] up to 1e9. I need to process subarrays defined by pairs, considering which indices are covered vs uncovered, counting elements in a multiset. I'll find an efficient way to compute contributions for indices that aren't covered by selected subarrays.

Thought for 8s

Risposta

cpp
long findTotalEfficiency(vector<int> arr, vector<vector<int>> pairs) { int n = arr.size(); // 1) Count how many times each index appears in the concatenated efficient array vector<long long> diff(n + 1, 0); for (auto &p : pairs) { int l = p[0]; int r = p[1]; diff[l]++; if (r + 1 < n) diff[r + 1]--; } vector<long long> cover(n, 0); long long cur = 0; for (int i = 0; i < n; i++) { cur += diff[i]; cover[i] = cur; } // 2) Coordinate compress arr values vector<int> vals = arr; sort(vals.begin(), vals.end()); vals.erase(unique(vals.begin(), vals.end()), vals.end()); int k = vals.size(); vector<long long> freq(k, 0); // freq[x] = how many times value x appears in efficient array for (int i = 0; i < n; i++) { if (cover[i] > 0) { int idx = lower_bound(vals.begin(), vals.end(), arr[i]) - vals.begin(); freq[idx] += cover[i]; } } // 3) Prefix sums: count of efficient elements with value <= vals[i] vector<long long> pref(k, 0); pref[0] = freq[0]; for (int i = 1; i < k; i++) { pref[i] = pref[i - 1] + freq[i]; } // 4) For indices not included in efficient array, count smaller values long long ans = 0; for (int i = 0; i < n; i++) { if (cover[i] == 0) { int idx = lower_bound(vals.begin(), vals.end(), arr[i]) - vals.begin(); if (idx > 0) { ans += pref[idx - 1]; } } } return ans; }

This handles duplicate intervals correctly because cover[i] stores how many times index i contributes to efficient.

Time complexity: O((n + m) log n)
Space complexity: O(n)

Condividi questa Q&A