hdu 2461(线段树求面积并)

题意:给出N个矩形,M次询问

每次询问给出R个,问这R个矩形围成的面积


解题思路:对于每次询问,做一次线段树求面积的并操作。

每个节点保存的信息有l,r,cover,len分别表示该节点表示的区间[l,r],该区间被线段完全覆盖的次数以及被线段覆盖的长度。



#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;

const int maxn = 25;
int n,m,edge[maxn],tmp[maxn];
int tmpsize,size;	//size表示线段树叶子节点个数

struct Segment
{
	int l,r,cover,len;
}tree[maxn<<2];
struct Rectangle
{
	int x1,x2,y1,y2;
}rec[maxn];
struct Line
{
	int x,y1,y2;
	int val;

	Line(){}
	Line(int _x,int _y1,int _y2,int _val)
	{
		x = _x;
		y1 = _y1;
		y2 = _y2;
		val = _val;
	}
};
vector<Line> vec;

void build(int rt,int l,int r)
{
	tree[rt].l = l, tree[rt].r = r;
	tree[rt].cover = tree[rt].len = 0;
	if(l + 1 == r || l == r) return;
	int mid = (l + r) >> 1;
	build(rt<<1,l,mid);
	build(rt<<1|1,mid,r);
}

void insert(int rt,int l,int r,int val)
{
	if(l <= tree[rt].l && tree[rt].r <= r)
	{
		tree[rt].cover += val;
		if(tree[rt].cover == 0)
			tree[rt].len = tree[rt<<1].len + tree[rt<<1|1].len;
		else tree[rt].len = edge[tree[rt].r] - edge[tree[rt].l];
		return;
	}
	int mid = (tree[rt].l + tree[rt].r) >> 1;
	if(l < mid) insert(rt<<1,l,r,val);
	if(mid < r) insert(rt<<1|1,l,r,val);
	if(tree[rt].cover == 0)
		tree[rt].len = tree[rt<<1].len + tree[rt<<1|1].len;
	else tree[rt].len = edge[tree[rt].r] - edge[tree[rt].l];
}

bool cmp(Line a,Line b)
{
	return a.x < b.x;
}

void DiscretData()  
{
	sort(tmp,tmp+tmpsize);
	size = 0;
	edge[++size] = tmp[0];
	for(int i = 1; i < tmpsize; i++)
		if(tmp[i] != tmp[i-1])
			edge[++size] = tmp[i];
}

int bisearch(int val)
{
	int l = 1, r = size, mid;
	while(l <= r)
	{
		mid = (l + r) >> 1;
		if(edge[mid] == val) return mid;
		else if(edge[mid] < val)
			l = mid + 1;
		else r = mid - 1;
	}
}

int main()
{
	int cas = 1;
	while(scanf("%d%d",&n,&m),n+m)
	{
		for(int i = 1; i <= n; i++)
			scanf("%d%d%d%d",&rec[i].x1,&rec[i].y1,&rec[i].x2,&rec[i].y2);
		printf("Case %d:\n",cas++);
		while(m--)
		{
			int r,q = 1;
			scanf("%d",&r);
			vec.clear();
			tmpsize = 0;
			for(int i = 1; i <= r; i++)
			{
				int k;
				scanf("%d",&k);
				vec.push_back(Line(rec[k].x1,rec[k].y1,rec[k].y2,1));
				vec.push_back(Line(rec[k].x2,rec[k].y1,rec[k].y2,-1));
				tmp[tmpsize++] = rec[k].y1;
				tmp[tmpsize++] = rec[k].y2;
			}
			DiscretData();
			sort(vec.begin(),vec.end(),cmp);
			build(1,1,size);
			int ans = 0;
			for(int i = 0; i < vec.size(); i++)
			{
				if(i > 0)
					ans += tree[1].len * (vec[i].x - vec[i-1].x);
				int l = bisearch(vec[i].y1);
				int r = bisearch(vec[i].y2);
				insert(1,l,r,vec[i].val);
			}
			printf("Query %d: %d\n",q++,ans);
		}
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值