Skip to content

Instantly share code, notes, and snippets.

@giantonia
Created December 16, 2016 07:13
Show Gist options
  • Save giantonia/843f36adfed5dac44f22e559cb3cd799 to your computer and use it in GitHub Desktop.
Save giantonia/843f36adfed5dac44f22e559cb3cd799 to your computer and use it in GitHub Desktop.
# python3
def parent_key_cal(key):
if key % 2 == 0:
parent_key = (key - 2)//2
else:
parent_key = (key - 1)//2
return parent_key
def swap(alist, key1, key2):
temp = alist[key1]
alist[key1] = alist[key2]
alist[key2] = temp
def siftup(alist, key):
child = alist[key]
parent_key = parent_key_cal(key)
parent = alist[parent_key]
while child > parent:
swap(alist, key, parent_key)
if parent_key != 0:
key = parent_key
parent_key = parent_key_cal(parent_key)
child = alist[key]
parent = alist[parent_key]
else:
break
def siftdown(alist, key):
parent = alist[key]
while len(alist) - 1 >= 2 * key + 1:
left = alist[2 * key + 1]
right = -1
if len(alist) - 1 >= 2 * key + 2:
right = alist[2 * key + 2]
if parent > left or (parent > right and right >= 0):
if parent > left and left > right:
swap(alist, key, 2 * key + 1)
key = 2 * key + 1
elif parent > right and right > left:
swap(alist, key, 2 * key + 2)
key = 2 * key + 2
else:
break
def heap_extract(alist):
swap(alist, 0, -1)
a = alist[-1]
alist.pop()
if len(alist) > 0:
siftdown(alist, 0)
return a
def heap_insert(alist, value):
alist.append(value)
siftup(alist, len(alist) - 1)
line1 = input().split()
n = int(line1[0])
m = int(line1[1])
line2 = input().split()
jobs = []
for i in range(len(line2)):
jobs.append(int(line2[i]))
threads = []
for i in range(n):
threads.append(i)
processing = []
time = 0
record = []
while len(jobs) > 0:
count = 0
while count < len(processing):
if processing[count][1] == 1:
a = processing.pop(count)
heap_insert(threads, a[0])
else:
processing[count][1] -= 1
count += 1
while len(jobs) > 0 and len(threads) > 0:
b = heap_extract(threads)
processing.append([b, jobs.pop(0)])
record.append([b, time])
time += 1
for i in range(m):
print(str(record[i][0]) + ' ' + str(record[i][1]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment