動機

被這題搞了兩天,所以要記錄下來 以前沒有看線段合併的Divide and Conquer,所以要記錄下來 (還債) 以前沒有看Segment tree,所以要記錄下來 (還債)

Problem

A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively.

The geometric information of each building is given in the array buildings where buildings[i] = [lefti, righti, heighti]:

  • lefti is the x coordinate of the left edge of the ith building.
  • righti is the x coordinate of the right edge of the ith building.
  • heighti is the height of the ith building.

You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.

The skyline should be represented as a list of key points sorted by their x-coordinate in the form [[x1,y1],[x2,y2],...]. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate 0 and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour.

Note: 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],...]

 

Example 1:

Input: buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]Output: [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]Explanation:Figure A shows the buildings of the input.Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list.

Example 2:

Input: buildings = [[0,2,3],[2,5,3]]Output: [[0,3],[5,0]]

 

Constraints:

  • 1 <= buildings.length <= 104
  • 0 <= lefti < righti <= 231 - 1
  • 1 <= heighti <= 231 - 1
  • buildings is sorted by lefti in non-decreasing order.

Ver1: Stack (many WA)

def retAppend(ret,p):
    #if not ret or ret[-1][1] != p[1]:
    ret.append(p)
def fg(stk,ret,b): # (stk,b) -> stk,ret
    print(b)
    print(ret,stk)
    if not stk:
        retAppend(ret,[b[0],b[2]]) # raise
        stk.append(b)
        return [stk,ret]
    else:
        now = stk[-1]
        if b[0] == now[0] and b[1] == now[1]: # same seg
            if b[2] > now[2]:
                stk.pop()
                stk.append(b)
                return [stk,ret]
            else:
                return [stk,ret]
        elif b[0] < now[1] and b[1] <= now[1]: # whole seg in roof
            if b[2] > now[2]:
                retAppend(ret,[b[0],b[2]]) # raise
                a = stk.pop()
                stk.append([b[1],a[1],a[2]])
                stk.append(b)
                return [stk,ret]
            else:
                return [stk,ret]
        elif b[0] < now[1] and now[1] < b[1]: # part of seg in roof
            if b[2] > now[2]:
                retAppend(ret,[b[0],b[2]])
                stk.pop()
                stk.append(b)
                return [stk,ret]
            elif b[2] == now[2]:
                tmp = stk.pop()
                stk.append([tmp[0],b[1],b[2]])
                return [stk,ret]
            else:
                tmp = stk.pop()
                a = [tmp[1],b[1],b[2]]
                return fg(stk,ret,a)
        elif b[0] == now[1]: # touch
            print(now,b,[now[1],now[2]])
            if b[2] > now[2]:
                retAppend(ret,[b[0],b[2]]) # raise
            elif b[2] < now[2]:
                retAppend(ret,[now[1],b[2]]) # fall
            stk.pop()
            stk.append(b)
            return [stk,ret]
        else: # seperate
            tmp = stk.pop()
            retAppend(ret,[tmp[1],0 if not stk else stk[-1][2]]) # fall
            return fg(stk,ret,b)
class Solution:
    def getSkyline(self, bs: List[List[int]]) -> List[List[int]]:
        if not bs:
            return []
        stk = []
        ret = []
        bs.sort(key=lambda b: (b[0],-b[2],b[1]))
        #print(bs)
        for b in bs:
            stk, ret = fg(stk,ret,b)
        retAppend(ret,[stk[-1][1],0])
        return ret

Ver2: Divide and Conquer (AC)

def div(bs,i,j):
    if i == j:
        return [[bs[i][0],bs[i][2]], [bs[i][1],0]]
    else:
        mid = (j+i)//2
        return merge(div(bs,i,mid), div(bs,mid+1,j))
def merge(a,b):
    ret = []
    i = 0
    j = 0
    h = 0
    h1 = 0
    h2 = 0
    while i < len(a) or j < len(b):
        if i < len(a) and j < len(b):
            cur = None
            if a[i][0] < b[j][0]:
                cur = a[i][0]
                h1 = a[i][1]
                i+=1
            elif a[i][0] > b[j][0]:
                cur = b[j][0]
                h2 = b[j][1]
                j+=1
            else:
                cur = b[j][0]
                h1 = a[i][1]
                h2 = b[j][1]
                i += 1
                j += 1
            h = max(h1,h2)
            if not ret or ret[-1][1] != h:
                ret.append([cur, h])
        elif i < len(a):
            ret += a[i:]
            break
        else:
            ret += b[j:]
            break
    return ret

class Solution:
    def getSkyline(self, bs: List[List[int]]) -> List[List[int]]:
        if not bs:
            return []
        else:
            return div(bs,0,len(bs)-1)

Ver3: heap & Sweep Line (AC)

from heapq import *

def f(poses):
    hq = []
    ret = []
    for p in poses:
        if not hq or p[1] < 0: # start seg
            heappush(hq,p[1])
        else: # end seg
            hq.pop(hq.index(-p[1]))
            heapify(hq)
        if not hq:
            ret.append([p[0],0])
        else:
            if not ret:
                ret.append([p[0],-hq[0]])
            else:
                if ret[-1][0] == p[0] and p[1] < 0: # tete
                    if ret[-1][1] < -p[1]:
                        ret[-1][1] = -p[1]
                else:
                    if ret[-1][1] != -hq[0]: # height changed
                        ret.append([p[0],-hq[0]])
                    else:
                        pass
    return ret

class Solution:
    def getSkyline(self, bs: List[List[int]]) -> List[List[int]]:
        if not bs:
            return []
        else:
            poses = []
            for b in bs:
                poses.append([b[0],-b[2]])
                poses.append([b[1],b[2]])
            poses.sort(key= lambda p: (p[0],p[1]))
            return f(poses)
from sortedcontainers import SortedList

def f(poses):
    hq = SortedList()
    ret = []
    for p in poses:
        if not hq or p[1] < 0: # start seg
            hq.add(p[1])
        else: # end seg
            del hq[hq.bisect_left(-p[1])]
        if not hq:
            ret.append([p[0],0])
        else:
            if not ret:
                ret.append([p[0],-hq[0]])
            else:
                if ret[-1][0] == p[0] and p[1] < 0: # tete
                    if ret[-1][1] < -p[1]:
                        ret[-1][1] = -p[1]
                else:
                    if ret[-1][1] != -hq[0]: # height changed
                        ret.append([p[0],-hq[0]])
                    else:
                        pass
    return ret

class Solution:
    def getSkyline(self, bs: List[List[int]]) -> List[List[int]]:
        if not bs:
            return []
        else:
            poses = []
            for b in bs:
                poses.append([b[0],-b[2]])
                poses.append([b[1],b[2]])
            poses.sort(key= lambda p: (p[0],p[1]))
            return f(poses)

Ref

[翻译]扫描线算法(Line Sweep Algorithm)(1) Chapter9 線段樹與相關結構