这是亚麻OA题
问题描述:
给一个 int[] arrival time, int[] Execution time, int q. 例子: 【0,1,4】 【5,2,3】 q=3. 输出的是average wait time 2.3333333
#include <iostream> // std::cout #include <algorithm> // std::make_heap, std::pop_heap, std::push_heap, std::sort_heap #include <vector> // std::vector #include <unordered_map> #include <unordered_set> #include <numeric> #include <sys/time.h> #include <list> #include <map> //main point : ( refer to key data structure and the trick. ) //introduce a timer (int ) to mark the current time. // //use map that can sort all the items to load the each job [Atime, Etime] // //compare the each current job ( map.begin()) with the timer and get the steps the timer will move forward and the remaing time if the running time is long. using namespace std; float RoundBin( vector<int>& Atime, vector<int>& Etime, int q){ if (q < 1 || Atime.size() == 0 || Etime.size()==0|| Atime.size() != Etime.size()) return 0; map<int , int > jobs; auto num = Atime.size(); //initialize the jobs. for (int i =0; i< num; i++) jobs[Atime[i]] = Etime[i]; int timer = 0; int waiting = 0; while (jobs.size() >0){ auto curJob = * jobs.begin(); // no job runing at this time. if (timer < curJob.first){ timer ++; continue; } int steps = min(q, curJob.second); waiting += timer - curJob.first; timer += steps; cout << "the start time is " << curJob.first << "waitint time is " << waiting << " after running the timer is " << timer << endl; //if the cucrent jobs is not done completely, save the remaining work load. int remains = curJob.second - steps; if ( remains > 0){ jobs[timer] = remains; cout << "insert a new job start " << timer << " runing " << remains<< endl; } jobs.erase( curJob.first); } cout <<"waiting time is " << waiting << " num is "<< num << endl; return waiting /(float) num; } int main () { //get the start time. struct timeval tv; gettimeofday(&tv,NULL); long ts = tv.tv_sec * 1000 + tv.tv_usec / 1000; //*** call the function . vector<int > in1 = {0,1,4}; vector<int > in2 = {5, 2 ,3}; int q = 3; cout <<" the waiting time is : " << RoundBin(in1, in2, q) << endl; //*** end of the call //get the time of end. gettimeofday(&tv,NULL); long te = tv.tv_sec * 1000 + tv.tv_usec / 1000; //output the time of the running. cout<<endl<< endl<< "running tmie is : " << te - ts << endl; return 0; }