现在的位置: 首页 > 综合 > 正文

多cpu作业调度算法 (贪心算法)

2013年09月12日 ⁄ 综合 ⁄ 共 1978字 ⁄ 字号 评论关闭

算法思想: 把作业时间从大到小排序,选择未安排cpu的最长作业到累积时间最短的一个cpu上,直至所有作业都被安排完。

                    使用堆排序,降低时间复杂度,用数组建立堆,cpu堆(小根堆)的每个节点指向一个作业链表。作业堆为大根堆。

#include <iostream>
#include <string>

using namespace std;

struct Node{
string name;
int length;
Node * next;
};
struct cpu{
string name;
int hight;
Node * first;
};

cpu * p=NULL;int psize=0;
Node * q=NULL;int qsize=0;
void siftP(int start,int end)
{
//小跟堆的筛选函数 
int t=(start+1)*2-1;
while(t<=end)
{
int temp=start;
if(p[temp].hight>p[t].hight)
temp=t;
if(t+1<=end&&p[temp].hight>p[t+1].hight)
temp=t+1;
if(temp==start)
break;
else
{
cpu CPU=p[start];
p[start]=p[temp];
p[temp]=CPU;
start=temp;
t=(start+1)*2-1;
}
}
}
void siftQ(int start,int end)
{
//大根堆的筛选函数
int t=2*(start+1)-1;
while(t<=end)
{
int temp=start;
if(q[temp].length<q[t].length)
temp=t;
if(t+1<=end&&q[temp].length<q[t+1].length)
temp=t+1;
if(temp==start)
break;
else
{
Node NODE=q[start];
q[start]=q[temp];
q[temp]=NODE;
start=temp;
t=(start+1)*2-1;
}
}
}
void Init()
{
cout<<"请输入cpu数量:\n";
int t;
cin>>t;psize=t;
p=new cpu[t];
for(int i=0;i!=t;++i)
{
string temp("CPU");
temp+=char('0'+i);
p[i].name=temp;
p[i].hight=0;
p[i].first=NULL;
}
cout<<"请输入作业的数量:\n";
cin>>t;qsize=t;
q=new Node[t];
for(int i=0;i!=t;++i)
{
cout<<"请输入作业"<<i+1<<"的名字:\n";
cin>>q[i].name;
cout<<"请输入作业"<<i+1<<"的时间片长度:\n";
cin>>q[i].length;
q[i].next=NULL;
}
t=qsize/2-1;
while(t>=0)
{
siftQ(t,qsize-1);
t--;
}
}
void Distribute()
{
for(int i=0;i!=qsize;++i)
{
Node * t=new Node ;
t->length=q[0].length;
t->name=q[0].name;
t->next=p[0].first;
p[0].first=t;//将当前最长作业加到cpu小根堆的堆顶cpu上
p[0].hight=p[0].hight+t->length;
siftP(0,psize-1);//重新筛选cpu小根堆
Node temp=q[0];
q[0]=q[qsize-1-i];
q[qsize-1-i]=temp;
siftQ(0,qsize-2-i);//重新筛选作业大根堆
}
}
void Release()
{
for(int i=0;i!=psize;++i)
{
Node * t=p[i].first;
while(t)
{
Node * temp=t;
t=t->next;
delete temp;
}
}
delete[] p;
delete[] q;
}
void main()
{
Init();
Distribute();
cout<<"完成所有作业的最短时间为:\n";
int max=0;
for(int i=0;i!=psize;++i)
{
if(p[i].hight>max)
max=p[i].hight;
}
cout<<max<<endl;
cout<<"调度安排如下:\n";
for(int i=0;i!=psize;++i)
{
cout<<p[i].name<<"的作业安排:";
Node * t=p[i].first;
while(t)
{
cout<<"作业:"<<t->name<<" 时间片:"<<t->length<<",";
t=t->next;
}
}
Release();
::system("pause");
}

抱歉!评论已关闭.