Johnson Rule

#include<bits/stdc++.h>
#define ll long long

struct JohnsonRule
{ 
    // Schedule jobs for 2 machines     
    struct Job {
        int time_a, time_b;
        int min_time;
        int idx;
        
        Job(int idx_, int time_a_, int time_b_) {
            idx = idx_; time_a = time_a_; time_b = time_b_;
            min_time = time_a < time_b ? time_a : time_b;
        }
    
        bool operator < (Job j) const {
            return min_time < j.min_time;
        }
        
    };
    
    vector<Job> jobs;
    
    void addJob(int x_time, int y_time) {
        int njob = jobs.size();
        Job j(njob, x_time, y_time);
        
        jobs.push_back(j);
                
    }
    
    pair< vector<int>, ll > scheduleJobs() {
        vector<int> queue_a, queue_b;
        
        sort(jobs.begin(), jobs.end());
        for (int j = 0; j < jobs.size(); ++j) {
            
            if (jobs[j].time_a < jobs[j].time_b)
                queue_a.push_back(j);
            else
                queue_b.push_back(j);
        }
        
        vector<int> job_queue(queue_a);
        job_queue.insert(job_queue.end(), queue_b.rbegin(), queue_b.rend());
        
        ll elapsed_a = 0, elapsed_b = 0;
        
        for (int j : job_queue) {
            elapsed_a += jobs[j].time_a;
            
            if (elapsed_a > elapsed_b)
                elapsed_b = elapsed_a;
            elapsed_b += jobs[j].time_b;
            
        }
        
        vector<int> schedule;
        for (int j : job_queue)
            schedule.push_back(jobs[j].idx);
        
        return make_pair(schedule, elapsed_b);
        
    }
};

Leave a Reply