将所有x坐标排序去重,则对于每一个相邻x组成的区间,要么完全可见,要么完全被遮挡。所以,可以用区间上一点(比如中点)来判断。
再判断,如果一个建筑,有在一个x区间上可见,即可见。
在一个区间上可见,需要在他的南边,没有比他更高的建筑。
ps:
1.结构体重载运算符函数本身记得要是const的,不然编译错误。
2.unique的使用需要先排序,并且unique并不删除元素,只是将重复元素移到了后面。
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
using namespace std;
const int maxn = 105;
struct building{
int id;
double x,y,w,d,h;
bool operator < (const building &a) const
{
return x < a.x || (x == a.x && y < a.y);
}
}b[maxn];
double x[maxn * 2];
bool cover(int id,double mx)
{
return b[id].x <= mx && mx <= b[id].x + b[id].w;
}
bool visi(int id,double mx,int n)
{
if (!cover(id,mx)) {
return false;
}
for (int k = 0; k < n; k ++) {
if (b[k].y < b[id].y && b[k].h >= b[id].h && cover(k,mx)) {
return false;
}
}
return true;
}
int main()
{
int n;
int cnt = 0;
while(cin >> n && n){
if (cnt) {
printf("\n");
}
memset(x, 0, sizeof(x));
for (int i = 0; i < n; i ++) {
scanf("%lf%lf%lf%lf%lf",&b[i].x,&b[i].y,&b[i].w,&b[i].d,&b[i].h);
b[i].id = i + 1;
x[i * 2] = b[i].x;
x[i * 2 + 1] = b[i].w + b[i].x;
}
sort(x ,x + 2 * n );
sort(b ,b + n );
int m = unique(x ,x + n * 2) - x ;
vector<int> ans;
printf("For map #%d, the visible buildings are numbered as follows:\n",++cnt);
for (int i = 0; i < n; i ++) {
bool vis = false;
for (int j = 0; j < m; j ++) {
if (visi(i,(x[j] + x[j + 1]) / 2,n) ){
vis = true;
ans.push_back(b[i].id);
break;
}
}
}
printf("%d",ans[0]);
for (int i = 1; i < ans.size(); i ++) {
printf(" %d",ans[i]);
}
printf("\n");
}
return 0;
}