AcWing 248 窗内的星星 (扫描线)

https://www.acwing.com/problem/content/description/250/

考虑以矩形的右上角代表这个矩形,
对于每个星星,考虑能圈住这个星星的矩形的右上角的范围,又因为矩形边界上的星星不算,
所以我们可以假设将星星的横纵坐标都减去\(0.5\),这样矩形的范围就是左下角为\((x,y)\),右上角为\((x - 1 + W, y - 1 + H)\)

对于这样的每个矩形区域,左右两边分别建立一条线段,用扫描线统计答案即可
要注意的是,线段不只要按横坐标排序,横坐标相同时,属于矩形左边的线段要排在属于矩形右边线段的后面,否则两个矩形的边界处答案可能会出错

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<stack>
#include<queue>
using namespace std;
typedef long long ll;

const int maxn = 200100;

int n, cnt, tot;
ll val[maxn];
ll ans, W, H;
ll x[maxn], y[maxn], c[maxn], Y[maxn];

struct Node{
	ll x, y1, y2, v;
	
	bool operator < (const Node &a) const { // 结构体内重载小于号 
		if(x == a.x){
			return v > a.v;
		}
		return x < a.x;
	}
}s[maxn << 1];

struct SEG{
	ll add, mx;
}t[maxn << 4];

void pushup(int i){ t[i].mx = max(t[i << 1].mx, t[i << 1 | 1].mx); }

void pushdown(int i, int l, int r){
	if(t[i].add){
		t[i << 1].add += t[i].add;
		t[i << 1 | 1].add += t[i].add;
		t[i << 1].mx += t[i].add;
		t[i << 1 | 1].mx += t[i].add; 
		t[i].add = 0;
	}
}

void modify(int i, int k, int l, int r, int x, int y){
	if(x <= l && r <= y){
		t[i].add += k; t[i].mx += k;
		return;
	}
	
	pushdown(i, l, r);
	int mid = (l + r) >> 1;
	if(x <= mid) modify(i << 1, k, l, mid, x, y);
	if(y > mid) modify(i << 1 | 1, k, mid + 1, r, x, y);
	pushup(i);
}

void init(){
	cnt = 0; tot = 0; ans = 0;

	for(int i = 1; i <= n; ++i){
		scanf("%lld%lld%lld", &x[i], &y[i], &c[i]);
		Y[++cnt] = y[i], Y[++cnt] = y[i] - 1 + H;
	}
	sort(Y + 1, Y + 1 + cnt);
	cnt = unique(Y + 1, Y + 1 + cnt) - Y - 1;
		
	for(int i = 1; i <= n; ++i){
		s[++tot].x = x[i];
		s[tot].y1 = lower_bound(Y + 1, Y + 1 + cnt , y[i]) - Y;
		s[tot].y2 = lower_bound(Y + 1, Y + 1 + cnt , y[i] - 1 + H) - Y;
		s[tot].v = c[i];
		
		s[++tot].x = x[i] - 1 + W;
		s[tot].y1 = lower_bound(Y + 1, Y + 1 + cnt , y[i]) - Y;
		s[tot].y2 = lower_bound(Y + 1, Y + 1 + cnt , y[i] - 1 + H) - Y;
		s[tot].v = -c[i];
	}
	
	sort(s + 1, s + 1 + tot);
}

void solve(){
	for(int i = 1; i <= tot; ++i){
		ans = max(ans, t[1].mx);
		modify(1, s[i].v, 1, cnt, s[i].y1, s[i].y2 - 1);
	}
	printf("%lld\n",ans);
}

ll read(){ ll s=0,f=1; char ch=getchar(); while(ch<'0' || ch>'9'){ if(ch=='-') f=-1; ch=getchar(); } while(ch>='0' && ch<='9'){ s=s*10+ch-'0'; ch=getchar(); } return s*f; }

int main(){
	while(scanf("%d%lld%lld", &n, &W, &H) != EOF){
		memset(t, 0, sizeof(t));
		init();
		solve();
	}
	
	return 0;
}
posted @ 2020-11-11 15:49  Tartarus_li  阅读(100)  评论(0编辑  收藏  举报