Advertisement
alisadafi

SkyLine-Practical-D&C

Apr 19th, 2024
666
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.20 KB | None | 0 0
  1. class Building:
  2.     def __init__(self, left, ht, right):
  3.         self.left = left
  4.         self.ht = ht
  5.         self.right = right
  6.  
  7. class Strip:
  8.     def __init__(self, left=0, ht=0):
  9.         self.left = left
  10.         self.ht = ht
  11.  
  12. class SkyLine:
  13.     def __init__(self, cap):
  14.         self.arr = []
  15.         self.capacity = cap
  16.         self.n = 0
  17.  
  18.     def count(self):
  19.         return self.n
  20.  
  21.     def merge(self, other):
  22.         res = SkyLine(self.n + other.n)
  23.         h1, h2, i, j = 0, 0, 0, 0
  24.         while i < self.n and j < other.n:
  25.             if self.arr[i].left < other.arr[j].left:
  26.                 x1, h1 = self.arr[i].left, self.arr[i].ht
  27.                 maxh = max(h1, h2)
  28.                 res.append(Strip(x1, maxh))
  29.                 i += 1
  30.             else:
  31.                 x2, h2 = other.arr[j].left, other.arr[j].ht
  32.                 maxh = max(h1, h2)
  33.                 res.append(Strip(x2, maxh))
  34.                 j += 1
  35.         while i < self.n:
  36.             res.append(self.arr[i])
  37.             i += 1
  38.         while j < other.n:
  39.             res.append(other.arr[j])
  40.             j += 1
  41.         return res
  42.  
  43.     def append(self, st):
  44.         if self.n > 0 and self.arr[self.n-1].ht == st.ht:
  45.             return
  46.         if self.n > 0 and self.arr[self.n-1].left == st.left:
  47.             self.arr[self.n-1].ht = max(self.arr[self.n-1].ht, st.ht)
  48.             return
  49.         self.arr.append(st)
  50.         self.n += 1
  51.  
  52.     def print_skyline(self):
  53.         print("Skyline for given buildings is")
  54.         for i in range(self.n):
  55.             print(" ({}, {}),".format(self.arr[i].left, self.arr[i].ht), end="")
  56.         print()
  57.  
  58. def find_skyline(arr, l, h):
  59.     if l == h:
  60.         res = SkyLine(2)
  61.         res.append(Strip(arr[l].left, arr[l].ht))
  62.         res.append(Strip(arr[l].right, 0))
  63.         return res
  64.     mid = (l + h) // 2
  65.     sl = find_skyline(arr, l, mid)
  66.     sr = find_skyline(arr, mid+1, h)
  67.     res = sl.merge(sr)
  68.     return res
  69.  
  70. arr = [Building(1, 11, 5), Building(2, 6, 7), Building(3, 13, 9), Building(12, 7, 16), Building(14, 3, 25), Building(19, 18, 22), Building(23, 13, 29), Building(24, 4, 28)]
  71. n = len(arr)
  72. skyline = find_skyline(arr, 0, n-1)
  73. skyline.print_skyline()
Tags: D&C
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement