Skip to content

Instantly share code, notes, and snippets.

@juanplopes
Created September 30, 2014 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanplopes/b6dc7da583254b81223e to your computer and use it in GitHub Desktop.
Save juanplopes/b6dc7da583254b81223e to your computer and use it in GitHub Desktop.
Simple scheduling algorithm in python (using Fenwick Trees)
class Fenwick:
def __init__(self, n):
self.n = n+1
self.T = [0] * self.n
def adjust(self, k, v):
k+=1
while k < self.n:
self.T[k] += v
k += k&-k
def rsq(self, b):
b+=1
result = 0
while b:
result += self.T[b]
b -= b&-b
return result
def schedule(tasks):
started = Fenwick(24)
finished = Fenwick(24)
def offer(begin, end):
result = started.rsq(end-1)-finished.rsq(begin)
started.adjust(begin, 1)
finished.adjust(end, 1)
return result+1
return ((offer(begin, end), (begin, end)) for begin, end in tasks)
for room, meeting in schedule([(12,13), (13,15), (19, 21), (18, 20), (17,20), (13,14)]):
print 'Meeting {} should occur in room {}'.format(meeting, room)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment