1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| class SegmentTree { public: std::vector<int> nodes; int n;
SegmentTree(const vector<int>& v) { n = v.size(); int h = std::ceil(std::log2(n)); nodes = std::vector<int>(2*std::pow(2,h)-1, 0);
build(v, 0, 0, n-1); }
int query(const vector<int>& v, int ql, int qr) const { return queryMin(v, 0, 0, n-1, ql, qr); }
private: int idOfMin(const vector<int>& v, int id1, int id2) const { if (id1 == INT_MAX) return id2; else if (id2 == INT_MAX) return id1;
return (v[id1] < v[id2]) ? id1 : id2; }
int queryMin(const vector<int>& v, int id, int l, int r, int ql, int qr) const { if (ql <= l && qr >= r) return nodes[id]; if (ql > r || qr < l) return INT_MAX;
int mid = l + (r - l) / 2; return idOfMin(v, queryMin(v, id*2+1, l, mid, ql, qr), queryMin(v, id*2+2, mid+1, r, ql, qr)); }
int build(const vector<int>& v, int id, int l, int r) { if (l == r) { return nodes[id] = l; }
int mid = l + (r-l)/2; return nodes[id] = idOfMin(v, build(v, id*2+1, l, mid), build(v, id*2+2, mid+1, r)); }
};
class Solution3 { public: int largestRectangleArea(vector<int> &height) { if (height.size() == 0) return 0; SegmentTree st(height); return dac(height, st, 0, height.size()-1); }
int dac(const vector<int>& height, const SegmentTree& st, int l, int r) { if (l > r) return -1; if (l == r) return height[l]; int id = st.query(height, l, r); return max(max(dac(height, st, l, id-1), dac(height, st, id+1, r)), (r-l+1)*height[id]); } };
|