问题
https://vjudge.net/problem/UVA-221
分析
一定要使用unique来去重,不去重就WA,想了半天没想明白为什么。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <map>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long LL;
const int maxn=100+5;
struct Point{
int id;
double x,y;
Point(int id=0,double x=0,double y=0, double height=0):id(id),x(x),y(y){}
// bool operator < (const Point &rhs) const {
// return x<rhs.x;
// }
};
struct Building{
int id;
double x1,x2,y,height;
Building(int id=0, double x1=0, double x2=0, double y=0, double height=0):id(id),
x1(x1),x2(x2),y(y),height(height){}
}building[maxn];
bool cmp1 (const Building &lhs,const Building &rhs) {
return lhs.y<rhs.y;
}
bool cmp2 (const Point &lhs,const Point &rhs) {
return lhs.x<rhs.x || (lhs.x==rhs.x && lhs.y<rhs.y);
}
int n,id,vis[maxn],kase=0;
double x,y,width,depth,height,pointx[2*maxn];
vector<Point> rec;
void find_building(double mid){
double preh=-1;
for(int i=0;i<n;++i){
Building &temp=building[i];
if(temp.x1<mid && temp.x2>mid){
if(vis[temp.id]==0 && temp.height>preh){
vis[temp.id]=1;
rec.push_back(Point(temp.id,temp.x1,temp.y));
}
//这一行语句得放在外面
preh=max(preh,temp.height);
}
}
}
int main(void){
while(scanf("%d",&n)==1 && n){
if(kase) printf("\n");
memset(vis,0,sizeof(vis));
int cnt=0;
for(int i=0;i<n;++i){
scanf("%lf%lf%lf%lf%lf",&x,&y,&width,&depth,&height);
pointx[cnt++]=x;
pointx[cnt++]=x+width;
building[i]=Building(i+1,x,x+width,y,height);
}
sort(pointx,pointx+cnt);
cnt=unique(pointx,pointx+cnt)-pointx;
sort(building,building+n,cmp1);
rec.clear();
for(int i=1;i<cnt;++i){
double mid=(pointx[i-1]+pointx[i])/2.0;
find_building(mid);
}
sort(rec.begin(),rec.end(),cmp2);
printf("For map #%d, the visible buildings are numbered as follows:\n",++kase);
printf("%d",rec[0].id);
for(int i=1;i<rec.size();++i) printf(" %d",rec[i].id);
printf("\n");
}
return 0;
}