HDU5091 Beam Cannon
一、题目大意
有个点(),点的坐标绝对值不超过,然后问你用一个的矩形,矩形的边平行于坐标轴,最多能盖住多少个点。
刘汝佳黑书上有原题



下面这份代码是加了离散化的,用垂直于轴的直线去扫描,在轴上建立线段树,所以对于每一个点,赋予权值,,然后增加一个新的负点,赋予权值。当扫描线扫过每一个点,用该点的权值去区间更新线段树。维护每个区间的值,因为是区间更新,所以还要打个标记。
二、实现代码
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
const int N = 40010;
struct Node {
int l, r, lazy;
int maxc;
} tr[N << 2];
struct Seg {
int x, y1, y2, c;
bool operator<(const Seg &t) const {
if (x == t.x) return c > t.c;
return x < t.x;
}
} seg[N << 1];
void pushup(int u) {
tr[u].maxc = max(tr[u << 1].maxc, tr[u << 1 | 1].maxc);
}
void pushdown(int u) {
if (tr[u].lazy) {
tr[u << 1].lazy += tr[u].lazy;
tr[u << 1 | 1].lazy += tr[u].lazy;
tr[u << 1].maxc += tr[u].lazy;
tr[u << 1 | 1].maxc += tr[u].lazy;
tr[u].lazy = 0;
}
}
void build(int u, int l, int r) {
tr[u] = {l, r, 0, 0};
if (l == r) return;
int mid = l + r >> 1;
build(u << 1, l, mid);
build(u << 1 | 1, mid + 1, r);
}
void modify(int u, int l, int r, int v) {
if (l <= tr[u].l && tr[u].r <= r) {
tr[u].lazy += v;
tr[u].maxc += v;
return;
}
pushdown(u);
int mid = tr[u].l + tr[u].r >> 1;
if (l <= mid) modify(u << 1, l, r, v);
if (r > mid) modify(u << 1 | 1, l, r, v);
pushup(u);
}
//离散化数组
vector<int> ys;
int find(int x) {
return lower_bound(ys.begin(), ys.end(), x) - ys.begin();
}
int main() {
//加快读入
ios::sync_with_stdio(false), cin.tie(0);
int n, w, h;
while (cin >> n && ~n) {
//多组数测数据
memset(tr, 0, sizeof tr);
ys.clear();
int idx = 0;
cin >> w >> h;
for (int i = 1; i <= n; i++) {
int x, y;
cin >> x >> y;
seg[++idx] = {x, y, y + h, 1};
seg[++idx] = {x + w, y, y + h, -1};
ys.push_back(y);
ys.push_back(y + h);
}
//对于边,按x由小到大,入边在前,出边在后排序
sort(seg + 1, seg + 1 + idx);
//离散化=排序+ 去重
sort(ys.begin(), ys.end());
ys.erase(unique(ys.begin(), ys.end()), ys.end());
//离散化似乎应该成为必要的步骤,这样记忆起来省的麻烦,都是一样的套路才方便记忆
build(1, 0, ys.size() - 1); // 0~ys.size()-1,共 ys.size()个,线段树是建立在y轴的投影上
int ans = 0;
for (int i = 1; i <= idx; i++) {
modify(1, find(seg[i].y1), find(seg[i].y2), seg[i].c);
ans = max(ans, tr[1].maxc);
}
printf("%d\n", ans);
}
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!