首页 > 其他分享 >P1502 窗口的星星

P1502 窗口的星星

时间:2024-07-20 19:18:14浏览次数:11  
标签:星星 P1502 窗口 int seg haxi vec y1 y2

原题链接

题解

1.首先要解决的问题是,怎样的窗口能包裹住尽可能多的星星?

这里有一个很巧妙的思维点,那就是我们构造一个以星星为左下角的矩形,矩形重叠的部分可以构造一个右上角在其中的窗口,这样这个窗口就能覆盖矩阵重合的星星

2.这样,问题就转换成了求最大并矩阵权值和(表示窗口的右上角在某个矩阵内),再转换一下,就变成了某条竖线上,区间重合最多的值
我们可以离散化+扫描线的方法来做,即构建一个y轴的线段树,然后把矩形分割开来(有点类似于差分),离散化是为了方便用线段树操作

code

#include <bits/stdc++.h>
#define ll long long
using namespace std;

vector<int> tree(800005, 0);        // 线段树数组
vector<int> lazytag(800005, 0);     // 延迟标记数组

struct node {
    int x, y1, y2, val;             // 节点结构体
    bool operator<(const node &b) const {
        if (x != b.x) return x < b.x;
        else return val < b.val;
    }
};

void build(int node, int l, int r) {
    tree[node] = 0;
    lazytag[node] = 0;
    if (l != r) {
        int mid = (l + r) / 2;
        build(node * 2, l, mid);
        build(node * 2 + 1, mid + 1, r);
    }
}

void pushdown(int node, int l, int r) {
    if (!lazytag[node]) return;
    tree[node] += lazytag[node];
    if (l != r) {
        lazytag[node * 2] += lazytag[node];
        lazytag[node * 2 + 1] += lazytag[node];
    }
    lazytag[node] = 0;
}

void update(int node, int l, int r, int x, int y, int val) {
    pushdown(node, l, r);
    if (l > y || r < x) return;

    if (l >= x && r <= y) {
        lazytag[node] += val;
        pushdown(node, l, r);
        return;
    }

    int mid = (l + r) / 2;
    update(node * 2, l, mid, x, y, val);
    update(node * 2 + 1, mid + 1, r, x, y, val);
    tree[node] = max(tree[node * 2], tree[node * 2 + 1]);
}

void solve() {
    int n, w, h;
    cin >> n >> w >> h;

    vector<node> seg;
    set<int> haxi;

    for (int i = 1; i <= n; i++) {
        int x, y, v;
        cin >> x >> y >> v;

        int endx = x + w;
        int y1 = y, y2 = y + h - 1;

        haxi.insert(y1);
        haxi.insert(y2);

        seg.push_back({x, y1, y2, v});
        seg.push_back({endx, y1, y2, -v});
    }

    vector<int> haxi_vec(haxi.begin(), haxi.end());
    int len = haxi_vec.size();

    build(1, 1, len);

    sort(seg.begin(), seg.end());

    int ans = 0;
    for (auto it : seg) {
        auto [x, y1, y2, val] = it;

        int pos1 = lower_bound(haxi_vec.begin(), haxi_vec.end(), y1) - haxi_vec.begin() + 1;
        int pos2 = lower_bound(haxi_vec.begin(), haxi_vec.end(), y2) - haxi_vec.begin() + 1;

        update(1, 1, len, pos1, pos2, val);
        ans = max(ans, tree[1]);
    }
    cout << ans << '\n';
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int t = 1;
    cin >> t;
    while (t--) solve();
    return 0;
}

标签:星星,P1502,窗口,int,seg,haxi,vec,y1,y2
From: https://www.cnblogs.com/pure4knowledge/p/18313614

相关文章