【练习12】 贪心算法 1004 Load Balancing

该博客介绍了使用贪心算法和优先队列解决Load Balancing问题的方法。作者强调了对任务按时间排序并分配给空闲时间最多的服务器的策略,并分享了因长时间未编程导致的编码困难经历,提醒读者编程需耐心与细致。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

算法思路:贪心 + 优先队列。

jobs需要先对时间排序,再依次选择time值最大的那个job,把它丢给运行时间最少的那个server(通过优先队列查找)。这个过程中要记录每次配对的job和server编号,最后一次性输出。

几天没有写代码,代码写得很挫,WA了无数遍,o(╯□╰)o coding是个伟大的工程,欲速则不达,还是十年磨一剑吧!

代码如下:

//模板开始
#include <string>   
#include <vector>   
#include <algorithm>   
#include <iostream>   
#include <sstream>   
#include <fstream>   
#include <map>   
#include <set>   
#include <cstdio>   
#include <cmath>   
#include <cstdlib>   
#include <ctime>
#include <iomanip>
#include <queue>
#include <string.h>
#define SZ(x) (int(x.size()))
using namespace std;

int toInt(string s){
	istringstream sin(s); 
	int t; 
	sin>>t; 
	return t;
}
template<class T> string toString(T x){
	ostringstream sout; 
	sout<<x; 
	return sout.str();
}
typedef long long int64;
int64 toInt64(string s){
	istringstream sin(s); 
	int64 t; 
	sin>>t;
	return t;
}
template<class T> T gcd(T a, T b){ 
	if(a<0) 
		return gcd(-a, b);
	if(b<0) 
		return gcd(a, -b);
	return (b == 0)? a : gcd(b, a % b);
}

#define LOCAL
//模板结束(通用部分)

struct Server
{
	int priority;
	int server_id;
	friend bool operator<(Server n1, Server n2)
	{
		return n1.priority > n2.priority;
	}
};

struct Job
{
	int job_id;
	int time;
	friend bool operator<(Job a, Job b)
	{
		return a.time > b.time;
	}
};

#define MAXN 100005
int cas;
int N, M;
priority_queue<Server> pq;
Server temp;
int d[MAXN];
Job e[MAXN];
int f[MAXN];

void init()
{
	while(!pq.empty())
	{
		pq.pop();
	}
	for(int i = 0; i < M; i++)
	{
		temp.server_id = i;
		temp.priority = 0;
		pq.push(temp);
	}
}

int main()
{
#ifdef LOCAL
	//freopen("shuju.txt", "r", stdin);
#endif

	int a;
	//cin>>cas;
	scanf("%d", &cas);
	for(int cc = 0; cc < cas; cc++)
	{
		//cin>>N>>M;
		scanf("%d%d", &N, &M);
		init();
		cout<<N<<endl;
		for(int i = 0; i < N; i++)
		{
			//cin>>a;
			scanf("%d", &e[i].time);
			e[i].job_id = i;
		}
		sort(e, e + N);
		/*cout<<endl;
		for(int i = 0; i < N; i++)
		{
			cout<<d[i]<<" ";
		}
		cout<<endl;*/
		for(int i = 0; i < N; i++)
		{
			temp = pq.top();
			pq.pop();
			temp.priority += e[i].time;
			pq.push(temp);
			int b = temp.server_id;
			int c = e[i].job_id;
			f[c] = b;
		}
		for(int i = 0; i < N; i++)
		{
			if(i == N - 1)
			{
				cout<<f[i];
			}
			else
			{
				cout<<f[i]<<" ";
			}
		}
		cout<<endl;
	}

	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值