summaryrefslogtreecommitdiff
path: root/sources/job_queue.py
blob: 8928d4a350324be4fff7ff934a353f4a17cda92b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# python3

from heapq import heappush, heappop
from collections import namedtuple

AssignedJob = namedtuple("AssignedJob", ["worker", "started_at"])


def assign_jobs(n_workers, jobs):
    # Naive algorithm
    result = []
    next_free_time = [0] * n_workers
    for job in jobs:
        next_worker = min(range(n_workers), key=lambda w: next_free_time[w])
        result.append(AssignedJob(next_worker, next_free_time[next_worker]))
        next_free_time[next_worker] += job

    return result


def assign_jobs_improved(n_workers, jobs):
    result = []
    worker_priority_q = []
    for i in range(n_workers):
        heappush(worker_priority_q, (0, i))

    for j in range(len(jobs)):
        pair = heappop(worker_priority_q)
        result.append(AssignedJob(pair[1], pair[0]))
        heappush(worker_priority_q, (pair[0] + jobs[j], pair[1]))

    return result


def main():
    n_workers, n_jobs = map(int, input().split())
    jobs = list(map(int, input().split()))
    assert len(jobs) == n_jobs

    assigned_jobs = assign_jobs_improved(n_workers, jobs)

    for job in assigned_jobs:
        print(job.worker, job.started_at)


if __name__ == "__main__":
    main()