Saturday, July 4, 2015

LeetCode [218] The Skyline Problem

 218. The Skyline Problem

Hard

A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Now suppose you are given the locations and height of all the buildings as shown on a cityscape photo (Figure A), write a program to output the skyline formed by these buildings collectively (Figure B).

Buildings Skyline Contour

The geometric information of each building is represented by a triplet of integers [Li, Ri, Hi], where Li and Ri are the x coordinates of the left and right edge of the ith building, respectively, and Hi is its height. It is guaranteed that 0 ≤ Li, Ri ≤ INT_MAX0 < Hi ≤ INT_MAX, and Ri - Li > 0. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.

For instance, the dimensions of all buildings in Figure A are recorded as: [ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24 8] ] .

The output is a list of "key points" (red dots in Figure B) in the format of [ [x1,y1], [x2, y2], [x3, y3], ... ] that uniquely defines a skyline. A key point is the left endpoint of a horizontal line segment. Note that the last key point, where the rightmost building ends, is merely used to mark the termination of the skyline, and always has zero height. Also, the ground in between any two adjacent buildings should be considered part of the skyline contour.

For instance, the skyline in Figure B should be represented as:[ [2 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ].

Notes:

  • The number of buildings in any input list is guaranteed to be in the range [0, 10000].
  • The input list is already sorted in ascending order by the left x position Li.
  • The output list must be sorted by the x position.
  • There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...[2 3], [4 5], [7 5], [11 5], [12 7]...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...[2 3], [4 5], [12 7], ...]
Use two priority queues queue_b and queue_h. Iterate through buildings and update queue_b and queue_h. Compute key points when 1) insert a new building to queue_b or 2) remove an old building form queue_b.
  • Iterate through buildings
  • A priority queue queue_b maintains the buildings such that
    • buildings in  queue_b are sorted in increasing order of Ri
    • every time a new building b is inserted (the inserting operation is denoted by I1) to queue_b, all the buildings with Ri<b.Li are removed (the removing operation is denoted by R1) from queue_b
  • A priority queue queue_h maintains the heights Hi of all the buildings in queue_b in decreasing order
    • every time the operation R1 is executed, remove the corresponding element in queue_h
  • Compute key point 
    1. I1: if b.Hi>queue_h.top(), (b.Lib.Hi) is a key point
    2. R1: when remove a building r from queue_b, if r.Hi>queue_h.top(), (r.Ri, queue_h.top()) is a key point
  • Potential problem: we need a remove function of queue_h, which is implemented by update_queue_h. Not efficient.
//C++: method1 TLE
class Solution {
    struct building{
        int l;
        int r;
        int h;
        bool operator<(const building& rhs) const{
            return r>rhs.r;
        }
        building(int l1, int r1, int h1):l(l1),r(r1),h(h1){}
    };
public:
    vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) {
        priority_queue<building> queue_b;
        priority_queue<int> queue_h;
        int c_queue = 0;
        vector<pair<int, int>> res;

        for(int i=0; i<buildings.size(); ++i){
            building b(buildings[i][0], buildings[i][1], buildings[i][2]);
            while(c_queue && queue_b.top().r<b.l)
                remove_buildings(queue_b, queue_h, res, c_queue);

            if(c_queue==0 || b.h>queue_h.top()){
                res.push_back(pair<int, int>(b.l, b.h));
            }
            queue_b.push(b);
            queue_h.push(b.h);
            c_queue++;
        }
        while(c_queue){
            remove_buildings(queue_b, queue_h, res, c_queue);
        }
        return res;
    }
    

    void remove_buildings(priority_queue<building> &queue_b, priority_queue<int> &queue_h, vector<pair<int, int>> &res, int &c_queue){
        building rb = queue_b.top();
        queue_b.pop();
        queue_h = update_queue_h(queue_b);
        if(queue_h.empty() || rb.h>queue_h.top()){
            res.push_back(pair<int, int>(rb.r, queue_h.empty()?0:queue_h.top()));
        }
        c_queue--;
    }

    priority_queue<int> update_queue_h(priority_queue<building> queue_b){
        priority_queue<int> queue_h;
        priority_queue<building> queue_b_t = queue_b;
        while(!queue_b_t.empty()){
            queue_h.push(queue_b_t.top().h);
            queue_b_t.pop();
        }
        return queue_h;
    }    
};
  1. Use a priority queue que to store active buildings. Each record of que has two elements: 
    1. The height Hi and the ending x-coordinate Ri  of the building. 
    2. Hi is the first key and Ri is the second key. So the buildings in que are ordered, first, in decrease order of Hi.
    3. If their Hi are equal, they are ordered in decreasing order of Ri.
  2. Repeatedly process the first element of que, denoted by t, to compute the next key point (X, Y)t is the building with the max height in que. The algorithm stops if
    1. there is no new building in buildings and 
    2. there is no active buildings in que
    1. Insert (X,Y) into res if Y is different from the last key point.
    //C++: 836ms
    class Solution {
    public:
        vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) {
            vector<pair<int, int>> res;
            priority_queue<pair<int, int>> que;
            int X, Y, i = 0, n = buildings.size();
            while(i<n || !que.empty()){
                    if(!que.empty() && (i==n || que.top().second<buildings[i][0])){
                        X = que.top().second;
                        while(!que.empty() && que.top().second<=X){
                            que.pop();
                        }
                    }else if(i<n){
                        X = buildings[i][0];
                        while(i<n && buildings[i][0]==X){
                            que.push(pair<int, int>(buildings[i][2], buildings[i][1]));
                            i++;
                        }
                    }
                    Y = que.empty()?0:que.top().first;
                    if(res.empty() || Y!=res.back().second){
                        res.push_back(pair<int, int>(X, Y));
                    }
            }
            return res;
        }
    };
    
    //Java
    class Pair{
        int height, right;
        Pair(int h, int r){
            height = h;
            right = r;
        }
       
        public String toString(){
            return height+" "+right;
        }
    };
    
    //ordered first in height, then in right.
    class PairComp implements Comparator<Pair>{
        public int compare(Pair p1, Pair p2){
            if(p1.height<p2.height) return 1;
            else if(p1.height==p2.height){
                if(p1.right<p2.right) return 1;
                if(p1.right==p2.right) return 0;
                else return -1;
            }else return -1;
        }
    };
    
    /*
    A point needs to be recorded in 3 cases:
    1. For a building B, if its top left conner is not overlapped, record it. 
    2. otherwise, it must be overlapped by a taller(or equal) building T.
        In this case, record <T.R, Y>, unless Y is not changed compared to the last record point.
    3. If B's bottom right conner is exposed, record it. 
    
    Create a priorityqueue(pq) to maintain the buildings. A building B is added to pq if it overlaps with the 
    tallest building T in pq. Buildings in pq are sorted in descending order is height first, and then in right.
    
    */
    public class Solution {
        public List<List<Integer>> getSkyline(int[][] buildings) {
            List<List<Integer>> ret = new ArrayList<>();
            PriorityQueue<Pair> pq = new PriorityQueue<Pair>(new PairComp());
            int i = 0, n = buildings.length;
            int X = 0, Y = 0;
            while(i<n || !pq.isEmpty()){
                if(!pq.isEmpty() && (i==n || pq.peek().right<buildings[i][0])){
                    X = pq.peek().right;
                    while(!pq.isEmpty()&&pq.peek().right<=X){
                        pq.poll();
                    }
                }else if(i<n){
                    X = buildings[i][0];
                    while(i<n && buildings[i][0]==X){
                        pq.add(new Pair(buildings[i][2], buildings[i][1]));
                        i++;
                    }
                }
                Y = pq.isEmpty() ? 0 : pq.peek().height;
                if(ret.isEmpty() || Y!=ret.get(ret.size()-1).get(1))
                    ret.add(Arrays.asList(new Integer[]{Integer.valueOf(X), Integer.valueOf(Y)}));
            }
            return ret;
        }
    }
    

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    class Solution {
        public List<List<Integer>> getSkyline(int[][] buildings) {
            //height, right: high to low then right to left
            PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> {
                if(a[0]==b[0]) return b[1]-a[1];
                else return b[0]-a[0];
            });
    
            int i = 0, n = buildings.length;
            int X = 0, Y = 0;
            List<List<Integer>> ret = new ArrayList<>();
            while(!pq.isEmpty()||i<n){
                if(!pq.isEmpty() && (i==n || pq.peek()[1]<buildings[i][0])){
                    X = pq.peek()[1];
                    while(!pq.isEmpty() && pq.peek()[1]<=X) pq.poll();
                }else{
                    X = buildings[i][0];
                    while(i<n && buildings[i][0]==X){
                        pq.add(new int[]{buildings[i][2], buildings[i][1]});
                        i++;
                    }
                }
                Y = pq.isEmpty()?0:pq.peek()[0];
                if(ret.isEmpty() || Y!=ret.get(ret.size()-1).get(1)){
                    ret.add(Arrays.asList(new Integer[]{X, Y}));
                }
            }
            
            return ret;
        }
    }
    

    No comments:

    Post a Comment