算法思想:长作业优先,先把作业分配给每台处理机,剩下的优先分配给先空闲的处理机。
#include<iostream> #include<algorithm> #include<vector> using namespace std; struct job { int id; int costtime; }; bool cmp(job a, job b) { return a.costtime > b.costtime; } int Greedy(vector<job> &j, int m) { int totle=0;//总花费时间 vector <int>q(m, 0); sort(j.begin(),j.end(),cmp); //将作业按从大到小排列 for (int i = 0; i < m; i++) { q[i] += j[i].costtime; }//将作业分配给所有空闲处理机 for (int i = m; i <j.size(); i++) { int minPosition = min_element(q.begin(), q.end()) - q.begin(); q[minPosition]+= j[i].costtime; }//将剩下作业分配给最先空闲的处理机 totle = *max_element(q.begin(), q.end()); return totle; } int main() { //输入作业数量 int n; cin >> n; vector<job> j; for (int i = 0; i < n; i++) { job j1; j1.id = i; cin >> j1.costtime; j.push_back(j1); } cout<<Greedy(j, 3); }