用二维线段树做太麻烦代码不好维护,纯离散化没ac,尽量使用stl。。。
不知道哪里错了,先记一下。
//纯离散化 O(n^3)复杂度
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
struct Rect
{
double left,top,right,bottom;
}rects[200];
bool blocks[1024][1024];
vector<double> xvec,yvec;
int BiSearch(vector<double>& vec,double key)
{
int low = 0,high = vec.size() - 1,mid;
double diff;
for (; ;)
{
mid = (low + high) / 2;
diff = key - vec[mid];
if (diff > 1e-10)
{
low = mid + 1;
}
else if (diff < -1e-10)
{
high = mid;
}
else
{
return mid;
}
}
return -1;//mute
}
inline bool double_equal(double elem1,double elem2)
{
return (fabs(elem1 - elem2) <= 1e-10);
}
inline void UniqueSort(vector<double>& vec)
{
sort(vec.begin(),vec.end());
vec.erase(unique(vec.begin(),vec.end(),double_equal),vec.end());
}
int main(void)
{
int t = 0,n;
xvec.reserve(200);
yvec.reserve(200);
int i,j,xstart,xend,ystart,yend,x,y;
double sum;
for (; ;)
{
scanf("%d",&n);
if (!n)
{
break;
}
//输入矩形
for (i = 0; i < n; ++i)
{
scanf("%lf%lf%lf%lf",&rects[i].left,&rects[i].top,&rects[i].right,&rects[i].bottom);
xvec.push_back(rects[i].left);
xvec.push_back(rects[i].right);
yvec.push_back(rects[i].top);
yvec.push_back(rects[i].bottom);
}
//排序,去重
UniqueSort(xvec);
UniqueSort(yvec);
//更新blocks数组
memset(blocks,sizeof(blocks),0);
for (i = 0; i < n; ++i)
{
xstart = BiSearch(xvec,rects[i].left);
xend = BiSearch(xvec,rects[i].right);
ystart = BiSearch(yvec,rects[i].top);
yend = BiSearch(yvec,rects[i].bottom);
for (x = xstart; x < xend; ++x)
for (y = ystart; y < yend; ++y)
{
blocks[x][y] = true;
}
}
//计算面积
sum = 0;
for (x = 0; x < xvec.size() - 1; ++x)
for (y = 0; y < yvec.size() - 1; ++y)
{
if (blocks[x][y])
{
sum += (xvec[x + 1] - xvec[x]) * (yvec[y + 1] - yvec[y]);
}
}
//输出
printf("Test case #%d/nTotal explored area: %.2lf/n/n",++t,sum);
}
return 0;
}
POJ1151 离散化
最新推荐文章于 2017-08-07 16:49:36 发布