Advertisement
nikunjsoni

497

May 13th, 2021
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.80 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<int> v;
  4.     vector<vector<int>> rects;
  5.    
  6.     int area(vector<int>& r) {
  7.         return (r[2] - r[0] + 1) * (r[3] - r[1] + 1);
  8.     }
  9.    
  10.     Solution(vector<vector<int>> _) {
  11.         rects = _;
  12.         for (auto& r : rects) {
  13.             v.push_back(area(r) + (v.empty() ? 0 : v.back()));
  14.         }
  15.     }
  16.    
  17.     vector<int> pick() {
  18.         // https://leetcode.com/problems/random-pick-with-weight/description/
  19.         int rnd = rand() % v.back();
  20.         auto it = upper_bound(v.begin(), v.end(), rnd);
  21.         int idx = it - v.begin();
  22.        
  23.         // pick a random point in rect[idx]
  24.         auto r = rects[idx];
  25.         return {
  26.             rand() % (r[2] - r[0] + 1) + r[0],
  27.             rand() % (r[3] - r[1] + 1) + r[1]
  28.         };
  29.     }
  30. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement