|
| 1 | + #include <iostream> |
| 2 | +#include <vector> |
| 3 | +#include <algorithm> |
| 4 | +#include <queue> |
| 5 | + |
| 6 | +using std::vector; |
| 7 | +using std::cin; |
| 8 | +using std::cout; |
| 9 | +using std::priority_queue; |
| 10 | + |
| 11 | + |
| 12 | +class worker |
| 13 | +{ |
| 14 | +public: |
| 15 | + long long int id; |
| 16 | + long long int next_free_time; |
| 17 | + worker(long long int id) |
| 18 | + { |
| 19 | + this->id=id; |
| 20 | + next_free_time=0; |
| 21 | + } |
| 22 | +}; |
| 23 | + |
| 24 | +struct compare{ |
| 25 | + bool operator()(const worker &w1, const worker &w2) const { |
| 26 | + if(w1.next_free_time == w2.next_free_time) |
| 27 | + return w1.id > w2.id; |
| 28 | + else |
| 29 | + return w1.next_free_time > w2.next_free_time; |
| 30 | + } |
| 31 | +}; |
| 32 | + |
| 33 | +class JobQueue { |
| 34 | + private: |
| 35 | + long long int num_workers_; |
| 36 | + vector<long long int> jobs_; |
| 37 | + |
| 38 | + vector<long long int> assigned_workers_; |
| 39 | + vector<long long int> start_times_; |
| 40 | + |
| 41 | + void WriteResponse() const { |
| 42 | + for (long long int i = 0; i < jobs_.size(); ++i) { |
| 43 | + cout << assigned_workers_[i] << " " << start_times_[i] << "\n"; |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + void ReadData() { |
| 48 | + long long int m; |
| 49 | + cin >> num_workers_ >> m; |
| 50 | + jobs_.resize(m); |
| 51 | + for(long long int i = 0; i < m; ++i) |
| 52 | + cin >> jobs_[i]; |
| 53 | + } |
| 54 | + |
| 55 | + void AssignJobs() { |
| 56 | + // TODO: replace this code with a faster algorithm. |
| 57 | + assigned_workers_.resize(jobs_.size()); |
| 58 | + start_times_.resize(jobs_.size()); |
| 59 | + priority_queue <worker, vector<worker>, compare> pq; |
| 60 | + long long int i=0; |
| 61 | + for(i=0;i<num_workers_;i++) |
| 62 | + { |
| 63 | + pq.push(worker(i)); |
| 64 | + } |
| 65 | + |
| 66 | + for (i = 0; i < jobs_.size(); ++i) { |
| 67 | + worker free_thread = pq.top(); |
| 68 | + pq.pop(); |
| 69 | + assigned_workers_[i] = free_thread.id; |
| 70 | + start_times_[i] = free_thread.next_free_time; |
| 71 | + free_thread.next_free_time += jobs_[i]; |
| 72 | + pq.push(free_thread); |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + public: |
| 77 | + void Solve() { |
| 78 | + ReadData(); |
| 79 | + AssignJobs(); |
| 80 | + WriteResponse(); |
| 81 | + } |
| 82 | +}; |
| 83 | + |
| 84 | + |
| 85 | + |
| 86 | +int main() { |
| 87 | + std::ios_base::sync_with_stdio(false); |
| 88 | + JobQueue job_queue; |
| 89 | + job_queue.Solve(); |
| 90 | + return 0; |
| 91 | +} |
0 commit comments