699. 掉落的方块https://leetcode.cn/problems/falling-squares/
在二维平面上的 x 轴上,放置着一些方块。
给你一个二维整数数组 positions ,其中 positions[i] = [lefti, sideLengthi] 表示:第 i 个方块边长为 sideLengthi ,其左侧边与 x 轴上坐标点 lefti 对齐。
每个方块都从一个比目前所有的落地方块更高的高度掉落而下。方块沿 y 轴负方向下落,直到着陆到 另一个正方形的顶边 或者是 x 轴上 。一个方块仅仅是擦过另一个方块的左侧边或右侧边不算着陆。一旦着陆,它就会固定在原地,无法移动。
在每个方块掉落后,你必须记录目前所有已经落稳的 方块堆叠的最高高度 。
返回一个整数数组 ans ,其中 ans[i] 表示在第 i 块方块掉落后堆叠的最高高度。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/falling-squares
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
借鉴到一个非常不错的线段树模板
class Node
{
public:
Node* left;
Node* right;
int l, r;
int mid;
int val;
int add;
Node(int l, int r) : l(l), r(r), mid((l + r) >> 1),
left(NULL), right(NULL), val(0), add(0) { };
};
class SegmentTree
{
private:
Node* root;
public:
SegmentTree()
{
root = new Node(1, 1e9);
}
void modify(int l, int r, int val)
{
modify(l, r, val, root);
}
void modify(int l, int r, int val, Node* node)
{
if (l > r) return;
if (node->l >= l && node->r <= r)
{
node->val = node->add = val;
return;
}
pushdown(node);
if (l <= node->mid) modify(l, r, val, node->left);
if (r > node->mid) modify(l, r, val, node->right);
pushup(node);
}
int query(int l, int r)
{
return query(l, r, root);
}
int query(int l, int r, Node* node)
{
if (l > r) return 0;
if (node->l >= l && node->r <= r) return node->val;
pushdown(node);
int v = 0;
if (l <= node->mid) v = max(v, query(l, r, node->left));
if (r > node->mid) v = max(v, query(l, r, node->right));
return v;
}
void pushup(Node* node)
{
node->val = max(node->left->val, node->right->val);
}
void pushdown(Node* node)
{
if (!node->left) node->left = new Node(node->l, node->mid);
if (!node->right) node->right = new Node(node->mid + 1, node->r);
if (node->add)
{
Node* left = node->left;
Node* right = node->right;
left->val = left->add =
right->val = right->add = node->add;
node->add = 0;
}
}
};
class Solution {
public:
vector<int> fallingSquares(vector<vector<int>>& positions) {
vector<int> ans;
SegmentTree tree;
int maxi = 0;
for (vector<int> p : positions)
{
int l = p[0];
int w = p[1];
int r = l + w - 1;
int h = tree.query(l, r) + w;
maxi = max(maxi, h);
ans.push_back(maxi);
tree.modify(l, r, h);
}
return ans;
}
};