【发布时间】:2017-08-28 04:41:48
【问题描述】:
https://www.hackerrank.com/challenges/minimum-average-waiting-time/problem 这是一个hackerrank问题的链接。我正在努力。 它通过了一些测试用例并失败了一些。我在 STL 中使用了内置的优先级队列模板。 代码如下,
#include<iostream>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
struct customer
{
long long arrTime;
long long cookTime;
long long index;
};
void swap(customer& a,customer& b)
{
customer &temp=a;
a=b;
b=temp;
}
bool compare( customer& a, customer& b)
{
return a.arrTime<b.arrTime;
}
struct Compare1
{
bool operator()(customer a,customer b)
{
return a.cookTime>b.cookTime;
}
};
struct Compare2
{
bool operator()(customer a,customer b)
{
return a.arrTime>b.arrTime;
}
};
int main()
{
vector<customer>c;
vector<bool>done;
long long n;
cin>>n;
for(long long i=0;i<n;i++)
{
customer cust;
cin>>cust.arrTime;
cin>>cust.cookTime;
cust.index=i;
c.push_back(cust);
done.push_back(false);
}
sort(c.begin(),c.end(),compare);
for(long long i=0;i<n-1;i++)
{
if(c[i].arrTime==c[i+1].arrTime && c[i].cookTime>c[i].cookTime)
{
swap(c[i],c[i+1]);
}
}
priority_queue<customer,vector<customer>,Compare1> waitList;
vector<long long>tat(n);
vector<long long>ct(n);
//next step- priority queue work starts
long long count=0;
long long totalTime=0;
long long i=0;
while(count!=n)
{
while(i<n && c[i].arrTime<=totalTime)
{
waitList.push(c[i]);
i++;
}
customer next;
if(!waitList.empty())
{
next=waitList.top();
//cout<<"Job "<<next.index<<endl;
waitList.pop();
totalTime+=next.cookTime;
ct[next.index]=totalTime;
done[next.index]=true;
count++;
}
else if(i<n)
{
next=c[i];
//cout<<"Job "<<next.index<<endl;
i++;
totalTime+=next.cookTime;
ct[next.index]=totalTime;
done[next.index]=true;
count++;
}
}
long long sum=0;
for(long long i=0;i<n;i++)
{
tat[i]=ct[i]-c[i].arrTime;
sum+=tat[i];
}
cout<<sum/n;
return 0;
}
我为这个问题查找了一种称为非抢占优先级调度的算法并实现了它。我的疑问: 这种调度算法是否适合该问题?我想知道我在调度算法的实现中是否有任何错误。 或任何其他算法来实现它。 这是变量名称的描述,
tat 数组代表作业的总周转时间
ct 数组代表完成时间。
我考虑过周转时间=非抢占式优先级调度的等待时间。
done 只是一个标志数组,用于指示标记为已完成的进程。
arrTime 表示到达时间。
cookTime 代表烹饪时间(而不是实际算法中过程的爆发时间)
【问题讨论】: