Manhattan skyline problem

老師給的一道算法作業題,要求O(nlgn)實現,題目如下:

 

 

Suppose that you are given the exact locations and shapes of several rectangular
buildings in a city, and you wish to draw the skyline (in two dimensions) of these
buildings, eliminating hidden lines. Assume that the bottoms of all the buildings lie on
a fixed line. Building Bi is represented by a triple (Li, Hi, Ri), where Li denotes the left
x-coordinate, Ri denote the right x-coordinate of the building, and Hi denotes the
building’s height. A skyline is a list of x coordinates and the heights connecting them
arranged in order from left to right. For example, the buildings in the figure 1 below
correspond to the following input (the numbers in boldface type are the heights):
(1, 7, 5), (9, 18, 12), (3, 3, 16), (15, 4, 18), (14, 13, 19).
Figure 1

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

The skyline (in bold) is represented as follows (again, the numbers in boldface type
are the heights):
(1, 7, 5, 3, 9, 18, 12, 3, 14, 13, 19).
(a) Given a skyline of n buildings and another skyline of m buildings, show how to
compute the combined skyline for the m + n buildings in O(m + n) steps.
(b) Give a divide and conquer algorithm to compute the skyline of a given set of n
buildings. Your algorithm should run in O(n log n) steps.
(c) Write a program to implement your algorithms
.

 

 

 

 

 

解:第一問要求用O(m+n)的複雜度實現兩個輪廓的合併,我們可以把輪廓用座標數組表示出來,然後在座標數組是進行操作,最後再用輪廓表示座標數組。示例如下:

     假設第一個輪廓線數組爲s1[1,5,3,7,5,4,7]

          第二個輪廓數組爲s2[2,9,6,3,9]

那麼我們可以用一個大小爲9的數組來表示這兩個輪廓(數組的下標代表座標系下的橫座標),有

               ss1[5,5,7,7,7,4,4,0,0] 

               ss2[0,9,9,9,9,9,3,3,3]

爲了編程方便以及和座標系的對應我們假設這兩個數組的下標都是從1開始的。根據題目的要求,可以通過比較ss1和ss2數組得到所求輪廓線的座標數組ss3[5,9,9,9,9,9,4,3,3],最後我們需要做的就是把座標數組ss3轉化爲輪廓線數組s3[1,5,2,9,6,4,7,3,9]。

程序清單如下:

 

 

 

第二問要求給定n個建築物各自的座標,求出它們總體的輪廓線。要求時間複雜度爲O(nlgn),並用分治算法,有了第一問的基礎,再借鑑歸併排序的算法思想,不難得出算法。只是在設計分治算法的時候怎麼設計數據結構才能實現遞歸函數要好好思考。這裏我把輪廓線當做一個結構體,如下:

typedef struct skyline

{

         int skylinenum;

         int sky[MAXNUM];

}*sky;

遞歸函數的參數爲輪廓線數組s[],數組的起始下標和結束下標m,n。具體實現見代碼清單:

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章