本文主要是介绍【华为笔试】抢占式任务调度,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
/****************************************************************************
问题描述:
//抢占式任务调度
//输入: 第一行 :n任务数
//接下来n行是任务信息 时间单位为 秒
//任务号 优先级 开始时间 运行时间
//输出:前200s 任务调度顺序
****************************************************************************/
#include "iostream"
#include <vector>#include "algorithm"
#include "string"
using namespace std;
//任务信息结构体
typedef struct{
int id;
int priority;
int startTime;
int runTime;
} Work;
//任务按照优先级降序排列
bool Less(const Work w1, const Work w2)
{
return w1.priority<w2.priority;
}
//正在运行任务信息
typedef struct{
int id;
int times;//已经运行的时间
} Working;
int main()
{
vector<Work> works(20); //最大任务数为20
int n;
cin >> n;//实际任务数
for (int ii = 0; ii<n; ii++)
{
cin >> works[ii].id >> works[ii].priority >> works[ii].startTime >> works[ii].runTime;
}
sort(works.begin(), works.begin() + n, Less);
vector< Working> workqueue;
for (int ii = 0; ii < n; ii++)
{
cout<< works[ii].id << works[ii].priority << works[ii].startTime << works[ii].runTime<<endl;
}
Working w;
workqueue.push_back(w);
//以分钟为刻度进行考虑
for (int ii = 0; ii<200; ii++)
{
for (int jj = 0; jj < n; jj++)
{
if (works[jj].startTime <= ii)
{
if (workqueue[workqueue.size() - 1].id == works[jj].id)
{
workqueue[workqueue.size() - 1].times++;
--works[jj].runTime;
if (works[jj].runTime == 0)
{
works.erase(works.begin()+jj);
n--;
}
}
else
{
w.id = works[jj].id;
w.times = 0;
workqueue.push_back(w);
}
break;
}
}
}
int size = workqueue.size();
for (int ii = 1; ii < size; ++ii)
{
cout <<"[ "<< workqueue[ii].id << " , " << workqueue[ii].times << " ]" << endl;
}
}
这篇关于【华为笔试】抢占式任务调度的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!