poj 1389 Area of Simple Polygons

还是矩形求并啊。。。原来这个做法就叫离散化+线扫描啊 = =。。。起这么个高深的名字干嘛。。。

unique函数,去除相邻的重复元素(只保留一个),它并不真正把重复的元素删除。

不过我觉得没必要用去重这个函数。。


#include <queue>
#include <stack>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <limits.h>
#include <string.h>
#include <string>
#include <algorithm>

using namespace std;

const int MAX = 1010;
struct rectangle{ int lx,ly,rx,ry;};
rectangle r[MAX];
bool map[MAX*2][MAX*2];
int x[MAX*2],y[MAX*2];
long long solve(int n,int cntx,int cnty)
{
	long long ans = 0ll;
	for(int i=0; i<n; i++)
	{
		int lx = lower_bound(x,x+cntx,r[i].lx) - x;
		int ly = lower_bound(y,y+cnty,r[i].ly) - y;
		int rx = lower_bound(x,x+cntx,r[i].rx) - x;
		int ry = lower_bound(y,y+cnty,r[i].ry) - y;
		for(int xx=lx; xx<rx; xx++)
			for(int yy=ly; yy<ry; yy++)
				map[xx][yy] = true;
	}
	for(int i=0; i<cntx-1; i++)
		for(int k=0; k<cnty-1; k++)
			if( map[i][k] )
				ans += (x[i+1] - x[i])*1ll*(y[k+1] - y[k]);
	return ans;
}
int main()
{
	int lx,ly,rx,ry;
	int n,cnt;
	
	while( ~scanf("%d%d%d%d",&lx,&ly,&rx,&ry) )
	{
		n = cnt = 0;
		memset(map,false,sizeof(map));
		if( lx < 0 ) break;
		r[n].lx = lx; r[n].ly = ly; r[n].rx = rx; r[n++].ry = ry;
		x[cnt] = lx; y[cnt++] = ly;
		x[cnt] = rx; y[cnt++] = ry;
		while( scanf("%d%d%d%d",&lx,&ly,&rx,&ry) )
		{
			if( lx < 0 ) break;
			r[n].lx = lx; r[n].ly = ly; r[n].rx = rx; r[n++].ry = ry;
			x[cnt] = lx; y[cnt++] = ly;
			x[cnt] = rx; y[cnt++] = ry;
		}
		sort(x,x+cnt); sort(y,y+cnt);
		int cntx = unique(x,x+cnt) - x;
		int cnty = unique(y,y+cnt) - y;
		long long ans = solve(n,cntx,cnty);
		printf("%lld\n",ans);
	}

return 0;
}


你可能感兴趣的:(poj 1389 Area of Simple Polygons)