#include <iostream>
using namespace std;
template <typename Type>
void Swap(Type& x, Type& y)
{
Type temp = x;
x = y;
y = temp;
}
template <typename Type>
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 <typename Type>
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 <typename Type>
MinHeap<Type> ::MinHeap(int m)
{
heap = new Type[m + 1];
length = 0;
}
template <typename Type>
void MinHeap<Type> ::Insert(const Type& x)
{
heap[++length] = x;
FilterUp();
}
template <typename Type>
void MinHeap<Type> ::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 <typename Type>
void MinHeap<Type> ::DeleteMin(Type& x)
{
x = heap[1];
heap[1] = heap[length];
length--;
FilterDown();
}
template <typename Type>
void MinHeap<Type> ::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 <typename Type>
MinHeap<Type> :: ~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 <typename Type>
void Greedy(JobNode a[], int n, int m)
{
if (n <= m){
cout << "为每个作业分配一台机器." << endl;
return;
}
Sort(a, n);
MinHeap <MachineNode> 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;
}