问题:设有n个独立的作业{1, 2, …, n}, 由m台相同的机器进行加工处理. 作业i所需时间为t i. 约定:任何作业可以在任何一台机器上加工处理, 但未完工前不允许中断处理,任何作业不能拆分成更小的子作业。要求给出一种作业调度方案,使所给的n 个作业在尽可能短的时间内由m台机器加工处理完成。
题解:先按照花费时间的长短从大到小排序,然后加入优先队列中。每次取优先队列的队首元素,加到总时间中。并把其他正在工作中的机器时间减去队首元素,模拟过程就是正确答案。
代码如下:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
priority_queue<int,vector<int>,greater<int> > q1;
priority_queue<int,vector<int>,greater<int> > q2;
int a[maxn];
bool cmp(int a,int b) {
return a>b;
}
int main(){
int n,m;
scanf("%d %d",&n,&m);
for(int i = 0 ; i < n ; i ++) cin >> a[i];
sort(a,a+n,cmp);
int k = n - m;
for(int i = 0 ; i < m ; i ++){
q1.push(a[i]);
}
int sumtime;
int cnt = 0;
while(cnt != k){
if(cnt%2 == 0){
int minx = q1.top();
sumtime += minx;
q1.pop();
while(!q1.empty()){
int now = q1.top();
q1.pop();
q2.push(now - minx);
}
q2.push(a[m+cnt]);
}
else{
int minx = q2.top();
sumtime += minx;
q2.pop();
while(!q2.empty()){
int now = q2.top();
q2.pop();
q1.push(now - minx);
}
q1.push(a[m+cnt]);
}
// cout << sumtime << endl;
cnt++;
}
int temp = -1;
if(!q1.empty()){
while(!q1.empty()){
temp = max(q1.top(),temp);
q1.pop();
}
}
else if(!q2.empty()){
while(!q2.empty()){
temp = max(q2.top(),temp);
q2.pop();
}
}
cout << sumtime + temp<< endl;
}
/*
7 3
16 14 6 5 4 3 2
*/