Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Something to learn: http://blog.csdn.net/yuwenshi/article/details/36666453

Shortest Job First Algorithm - kinda greedy: we do shorter job first BUT we only consider arrived jobs.

#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
#include <stack>
#include <cstring>
#include <climits>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <queue>
using namespace std;

struct Rec
{
    Rec(int s, int d) : start(s), duration(d){}
    int start;
    int duration;  
    
    bool operator < (const Rec& p) const {  
        return start < p.start;  
    }  
};

struct Cmp
{
    bool operator()(const Rec& p1, const Rec& p2) {  
        return p1.duration > p2.duration;  
    }
};

int main() 
{          

    int n; cin >> n;
    
    //    Get input and sort by arriving time
    vector<Rec> in;
    for(int i = 0; i < n; i ++)
    {
        int s, t; cin >> s >> t;
        in.push_back(Rec(s, t));
    }
    sort(in.begin(), in.end());
    
    //    Shortest Job First algorithm
    long long ans = 0, end = 0;
    priority_queue<Rec, vector<Rec>, Cmp> q;
    
    int i = 0;
    while ( i < n || !q.empty())
    {
        if (q.empty()) // some gap with NO customers
        {
            end = max(end, (long long)(in[i].start));
        }
        //    add all arrived customers
        while(i < n && in[i].start <= end)
        {
            q.push(in[i]);
            i ++;
        }
        Rec r = q.top();
        end += r.duration;
        ans += end - r.start;
        q.pop();
    }
    cout << ans / n << endl;
    return 0;
}
posted on 2015-11-19 07:20  Tonix  阅读(434)  评论(0编辑  收藏  举报