HDU 5091 Beam Cannon 线段树+扫描线

马上要写一道线段树+扫描线的题,先把很早之前写过的一道复习一下。


代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
struct edge_mode
{
	int y, l, r, val;
	void edge_make(int y,int l,int r,int val)
	{
		this->y = y;
		this->l = l;
		this->r = r;
		this->val = val;
	}
}edge[20005];
struct segment
{
	int add, max;
}segtree[160005];
bool cmp(edge_mode a, edge_mode b)
{
	if (a.y < b.y) return true;
	else return false;
}
void init(int id, int l, int r)
{
	segtree[id].add = segtree[id].max = 0;
	if (l == r) return;
	init(id << 1, l, (l + r) >> 1);
	init(id << 1 | 1, ((l + r) >> 1 )+ 1, r);
}
void update(int id, int l, int r, int nl, int nr, int val)
{
	if (r<nl || l>nr) return;
	if (l >= nl&&r <= nr)
	{
		segtree[id].add += val;
		segtree[id].max += val;
		return;
	}
	update(id << 1, l, (l + r) >> 1, nl, nr, val);
	update(id << 1 | 1, ((l + r) >> 1) + 1, r, nl, nr, val);
	segtree[id].max = max(segtree[id << 1].max, segtree[id << 1 | 1].max) + segtree[id].add;
}
int main()
{
	int n, w, h;
	while ((scanf("%d %d %d", &n, &w, &h)) == 3)
	{
		init(1, 0, 40000);
		for (int x = 0, y = 0, i = 0; i < n; i++)
		{
			scanf("%d %d", &x, &y);
			x += 20000; y += 20000;
			edge[2 * i].edge_make(y, x, x + w, 1);
			edge[2 * i + 1].edge_make(y + h + 1, x, x + w, -1);
		}
		sort(edge, edge + 2 * n, cmp);
		int ans = 0;
		for (int i = 0,t = 0; i <= 40000; i++)
		{
			while (edge[t].y == i&&t < 2 * n)
			{
				update(1, 0, 40000, edge[t].l, edge[t].r, edge[t].val);
				t++;
			}
			ans = max(ans, segtree[1].max);
		}
		printf("%d\n", ans);
	}
	return 0;
}

你可能感兴趣的:(HDU 5091 Beam Cannon 线段树+扫描线)