Created
September 30, 2014 14:51
-
-
Save juanplopes/b6dc7da583254b81223e to your computer and use it in GitHub Desktop.
Simple scheduling algorithm in python (using Fenwick Trees)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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