|
| 1 | +// Perfect Rectangle |
| 2 | +namespace std { |
| 3 | +template<> |
| 4 | + struct hash<pair<int, int>> { |
| 5 | + size_t operator()(const pair<int, int>& x) const { |
| 6 | + return size_t(x.first) << 32 | x.second; |
| 7 | + } |
| 8 | + }; |
| 9 | +}; |
| 10 | + |
| 11 | +class Solution { |
| 12 | +public: |
| 13 | + bool isRectangleCover(vector<vector<int>>& rectangles) { |
| 14 | + int x0 = INT_MAX, x1 = INT_MIN, y0 = INT_MAX, y1 = INT_MIN; |
| 15 | + unordered_map<pair<int, int>, int> m; |
| 16 | + for (auto& a: rectangles) { |
| 17 | + x0 = min(x0, a[0]); |
| 18 | + y0 = min(y0, a[1]); |
| 19 | + x1 = max(x1, a[2]); |
| 20 | + y1 = max(y1, a[3]); |
| 21 | + int& m1 = m[make_pair(a[0], a[1])]; if (m1 & 1) return false; m1 |= 1; |
| 22 | + int& m2 = m[make_pair(a[0], a[3])]; if (m2 & 2) return false; m2 |= 2; |
| 23 | + int& m4 = m[make_pair(a[2], a[3])]; if (m4 & 4) return false; m4 |= 4; |
| 24 | + int& m8 = m[make_pair(a[2], a[1])]; if (m8 & 8) return false; m8 |= 8; |
| 25 | + } |
| 26 | + for (auto& i: m) { |
| 27 | + int x, y, mask = i.second; |
| 28 | + tie(x, y) = i.first; |
| 29 | + if ((x == x0 || x == x1) && (y == y0 || y == y1)) { |
| 30 | + if (__builtin_popcount(mask) != 1) |
| 31 | + return false; |
| 32 | + } else { |
| 33 | + if (mask != 3 && mask != 6 && mask != 12 && mask != 9 && mask != 15) |
| 34 | + return false; |
| 35 | + } |
| 36 | + } |
| 37 | + return true; |
| 38 | + } |
| 39 | +}; |
| 40 | + |
| 41 | +/// sweep line |
| 42 | + |
| 43 | +class Solution { |
| 44 | +public: |
| 45 | + bool isRectangleCover(vector<vector<int>>& rectangles) { |
| 46 | + long area = 0, x0 = INT_MAX, x1 = INT_MIN, y0 = INT_MAX, y1 = INT_MIN; |
| 47 | + vector<pair<int, pair<int, int>>> b; |
| 48 | + set<pair<int, int>> active; |
| 49 | + for (auto& a: rectangles) { |
| 50 | + x0 = min(x0, long(a[0])); |
| 51 | + y0 = min(y0, long(a[1])); |
| 52 | + x1 = max(x1, long(a[2])); |
| 53 | + y1 = max(y1, long(a[3])); |
| 54 | + area += (long(a[2])-a[0])*(long(a[3])-a[1]); |
| 55 | + b.emplace_back(a[0]*2+1, make_pair(a[1], a[3])); |
| 56 | + b.emplace_back(a[2]*2, make_pair(a[1], a[3])); |
| 57 | + } |
| 58 | + sort(b.begin(), b.end()); |
| 59 | + for (auto& a: b) |
| 60 | + if (a.first % 2) { |
| 61 | + auto it = active.lower_bound(a.second); |
| 62 | + if (it != active.begin() && a.second.first < prev(it)->second || |
| 63 | + it != active.end() && it->first < a.second.second) |
| 64 | + return false; |
| 65 | + active.insert(it, a.second); |
| 66 | + } else |
| 67 | + active.erase(a.second); |
| 68 | + return area == (x1-x0)*(y1-y0); |
| 69 | + } |
| 70 | +}; |
0 commit comments