Advertisement
anechka_ne_plach

Untitled

Sep 26th, 2021
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <numeric>
  5. #include <future>
  6. #include <string>
  7. #include <mutex>
  8.  
  9. struct Request {
  10.     int left; int right;
  11. };
  12.  
  13. std::mutex m;
  14. struct X {
  15.     std::vector<std::vector<int>> nums;
  16.  
  17.     void make_rmq(const std::vector<int>& numbers) {
  18.         nums.emplace_back();
  19.         for (int i: numbers) {
  20.             nums[0].emplace_back(i);
  21.         }
  22.         for (int j = 1; pow(2, j) <= numbers.size(); ++j) {
  23.             nums.emplace_back();
  24.             for (int i = 0; i < numbers.size() - int(pow(2, j)) + 1; ++i) {
  25.                 nums[j].emplace_back(std::max(nums[j - 1][i], nums[j - 1][i + int(pow(2, j - 1))]));
  26.             }
  27.         }
  28.     }
  29.  
  30.     void process_partial(long long l, long long r, const std::vector<Request>& requests, std::vector<int>& ans) {
  31.         std::lock_guard<std::mutex> lk(m);
  32.         for (long long i = l; i < r; ++i) {
  33.             int lg = floor(log2(r - l));
  34.             ans[i] = std::max(nums[lg][requests[i].left], nums[lg][requests[i].right - int(pow(2, lg))]);
  35.         }
  36.     }
  37. };
  38.  
  39. std::vector<int> ProcessRequests(
  40.         const std::vector<int>& numbers, const std::vector<Request>& requests) {
  41.     X x;
  42.     x.make_rmq(numbers);
  43.     std::vector<int> ans(requests.size());
  44.     long long i0 = requests.size() / 4;
  45.     long long i1 = requests.size() / 2;
  46.     long long i2 = 3 * requests.size() / 4;
  47.     auto a1 = std::async(std::launch::deferred, &X::process_partial, &x, 0, i0, requests, ans);
  48.     auto a2 = async(&X::process_partial, &x, i0, i1, requests, ans);
  49.     auto a3 = async(&X::process_partial, &x, i1, i2, requests, ans);
  50.     auto a4 = async(&X::process_partial, &x, i2, requests.size(), requests, ans);
  51.     return ans;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement