算法导论实验——多机调度问题

题目:
例如,设7个独立作业{1,2,3,4,5,6,7}由3台机器M1,M2,M3加工处理。各作业所需的处理时间分别为{2,14,4,16,6,5,3}。按贪心算法求解最优的调度方案。

问题分析:
对于多机调度问题,采用最长处理时间作业优先的贪心选择策略:
当作业的个数小于等于机器的个数时,只要将机器i的[0,t[i]]时间区间分配给作业i即可;当作业的个数大于机器的个数时,首先将n个作业依次按所需处理时间从大到小排序,然后按照顺序将作业分配给空闲的处理机器。

实验源代码:

#include 
using namespace std;

template 
void Swap(Type& x, Type& y)
{
	Type temp = x;
	x = y;
	y = temp;
}

template 
void Sort(Type *a, int n)
{
	//对a[1..n]中n个元素进行排序(选择排序)
	for (int i = 1; i < n; i++)
	{
		int k = i;
		for (int j = i + 1; j <= n; j++)
		{
			//找出第i小的元素
			if (a[j] < a[k]){
				k = j;
			}
		}
		Swap(a[i], a[k]);
	}
}

template 
class MinHeap
{
public:
	MinHeap(int ms);
	~MinHeap();
	void Insert(const Type& x);
	void DeleteMin(Type& x);
protected:
	void FilterDown();      //自顶向下构造堆
	void FilterUp();        //自底向上构造堆
private:
	Type *heap;
	int length;
};

//初始化一个空堆
template 
MinHeap ::MinHeap(int m)
{
	heap = new Type[m + 1];
	length = 0;
}

template 
void MinHeap ::Insert(const Type& x)
{
	heap[++length] = x;
	FilterUp();
}

template 
void MinHeap ::FilterUp()
{
	//自底向上进行调整
	int  i = length, j = i / 2;       //父节点的编号
	Type temp = heap[i];
	while (i > 1)
	{
		if (temp >= heap[j]){
			break;              //找到了相应的位置
		}
		else {
			heap[i] = heap[j];
			i = j;
			j = i / 2;
		}
	}
	heap[i] = temp;
}

template 
void MinHeap ::DeleteMin(Type& x)
{
	x = heap[1];
	heap[1] = heap[length];
	length--;
	FilterDown();
}

template 
void MinHeap ::FilterDown()
{
	int i = 1, j = i * 2;
	Type temp = heap[i];
	while (j <= length)
	{
		if (j < length && heap[j] > heap[j + 1]){
			j++;        //如果左右子树都存在,找出最小者,用j标记
		}
		if (temp < heap[j]){
			break;       //找到了相应的位置
		}
		else {
			heap[i] = heap[j];
			i = j;
			j = 2 * i;
		}
	}
	heap[i] = temp;
}

template 
MinHeap :: ~MinHeap()
{
	delete[] heap;
}

class JobNode{
	friend void Greedy(JobNode*, int, int);
	friend int main(void);
public:
	operator int()  const{ return time; }
private:
	int ID,             //作业编号
		time;               //对应作业处理时间
};

class MachineNode{
	friend void Greedy(JobNode*, int, int);
public:
	operator int() const{ return avail; }
private:
	int ID,             //作业编号
		avail;              //
};

//template 
void Greedy(JobNode a[], int n, int m)
{
	if (n <= m){
		cout << "为每个作业分配一台机器." << endl;
		return;
	}
	Sort(a, n);
	MinHeap  H(m);
	MachineNode x;
	for (int i = 1; i <= m; i++){
		x.avail = 0;
		x.ID = i;
		H.Insert(x);
	}

	for (int i = n; i >= 1; i--){
		H.DeleteMin(x);
		cout << "将机器" << x.ID << "从" << x.avail << "到" << (x.avail + a[i].time) << "的时间段分配给作业" << a[i].ID << endl;
		x.avail += a[i].time;
		H.Insert(x);
	}
}

int main()
{
	int n;              //作业个数
	int m;              //机器台数
	cout << "请输入作业个数n和机器台数m:" << endl;
	cin >> n >> m;
	JobNode *b = new JobNode[n + 1];
	cout << "请输入对应作业号1-" << n << "的处理时间time:" << endl;
	for (int i = 1; i <= n; i++)
	{
		b[i].ID = i;
		cin >> b[i].time;
	}
	Greedy(b, n, m);
	delete[] b;
	return 0;
}

实验结果:
算法导论实验——多机调度问题_第1张图片

你可能感兴趣的:(算法导论)