贪心经典例题---多机调度问题(优先队列)

 问题:设有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
*/

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值