大楼轮廓

  Given N buildings in a x-axis,each building is a rectangle and can be represented by a triple (start, end, height),where start is the start position on x-axis, end is the end position on x-axis and height is the height of the building. Buildings may overlap if you see them from far away,find the outline of them。

An outline can be represented by a triple, (start, end, height), where start is the start position on x-axis of the outline, end is the end position on x-axis and height is the height of the outline.

 注意事项

  请注意合并同样高度的相邻轮廓,不同的轮廓线在x轴上不能有重叠。

#include <iostream>
#include <map>
#include <algorithm>
#include <list>
using namespace std;

typedef struct Node
{
    bool isUp;
    int height;
    int pos;
    Node ()
    {
        this->isUp=true;
        this->height=0;
        this->pos=0;
    }
    Node(bool _isUp,int h,int p)
    {
        this->isUp=_isUp;
        this->height=h;
        this->pos=p;
    }
    bool operator()(const Node &a,const Node &b)
    {
        return a.pos<=b.pos;
    }
        
}Node;

list<list<int> > building_outline(const vector<vector<int> > &a)
{
    list<list<int> > res;
    if(a.empty()||a.at(0).size()<=2)
        return res;
    
    map<int,int> bulidMap;
    map<int,int> resMap;
    vector<Node> node(a.size()*2);
    
    for(int i=0;i<a.size();++i)
    {
        node[i*2]=Node(true,a.at(i).at(2),a.at(i).at(0));
        node[i*2+1]=Node(false,a.at(i).at(2),a.at(i).at(1));
    }
    sort(node.begin(),node.end(),Node());

    for(auto it=node.begin();it!=node.end();++it)
    {
        //如果此点是楼上升的位置 
        if((*it).isUp)
        {
            if(bulidMap.count((*it).height)==0)
                bulidMap.insert({(*it).height,1});
            else
                ++bulidMap[(*it).height];
        }
        else//此点是楼下降的位置 
        {
            if(bulidMap.count((*it).height)==1)
                bulidMap.erase((*it).height);
            else
                --bulidMap[(*it).height];
        }
        
        if(bulidMap.empty())
            resMap.insert({(*it).pos,0});
        else
            resMap.insert({(*it).pos,(--bulidMap.end())->first});
    }
        
    int start=0,height=0;
    for(const auto &i:resMap)
    {
        int curStart=i.first;
        int curHeight=i.second;
        if(height!=curHeight)
        {
            if(height!=0)
            {
                list<int> l;
                l.push_back(start);
                l.push_back(curStart);
                l.push_back(height);
                res.push_back(l);
            }
            start=curStart;
            height=curHeight;
        }
    }
    return res;
}

int main()
{
    vector<vector<int> > a{{1,3,3},{2,4,4},{5,6,1}};
    list<list<int> > res=building_outline(a);
    
    for(const auto &it:res)
    {
        for(auto i=it.begin();i!=it.end();++i)
            cout<<*i<<" ";
        cout<<endl;
    }
    return 0;
}

 

posted on 2019-03-18 21:33  tianzeng  阅读(187)  评论(0编辑  收藏  举报

导航