标签:
#include <iostream> #include <vector> #include <stdlib.h> #include <algorithm> using namespace std; /********************题目要求*********************************** 最短左右优先,输出总等待时间 测试用例: 任务: A,B,C,D 请求时间:0,2,4,5 持续时间:7,4,1,4 求平均等待时间 ****************************************************************/ /********************解题思路*********************************** 请求时间 持续时间 开始时间 结束时间 等待时间 = 开始时间 - 请求时间 A 0 7 0 7 0 ---------------------------------------------------------- C 4 1 7 8 3 ---------------------------------------------------------- B 2 4 8 12 6 ---------------------------------------------------------- D 5 4 12 16 7 ****************************************************************/ void show(vector<int> &time) { for (int i = 0; i < time.size(); i++) cout << time[i] << " "; } float average_time(vector<int> &require_time, vector<int> &duration_time, int n) { for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if ((duration_time[i] > duration_time[j]) || ((duration_time[i] == duration_time[j]) && (require_time[i] > require_time[j]))) { duration_time[i] = duration_time[i] ^ duration_time[j]; duration_time[j] = duration_time[i] ^ duration_time[j]; duration_time[i] = duration_time[i] ^ duration_time[j]; require_time[i] = require_time[i] ^ require_time[j]; require_time[j] = require_time[i] ^ require_time[j]; require_time[i] = require_time[i] ^ require_time[j]; } } } int min = 0xFFFFFFFF, count = 0; vector<int> start_time(n), end_time(n),wait_time(n); int sum = 0; for (int i = 0; i < require_time.size(); i++) { if (require_time[i] < min) { min = require_time[i]; count = i; } else if (min == require_time[i]) { count = duration_time[count] < duration_time[i] ? duration_time[count] : duration_time[i]; } } duration_time.insert(duration_time.begin(), duration_time[count]); duration_time.erase(duration_time.begin()+ count + 1); require_time.insert(require_time.begin(), require_time[count]); require_time.erase(require_time.begin() + count + 1); start_time[0] = require_time[0]; end_time[0] = duration_time[0]; wait_time[0] = 0; for (int i = 1; i < n; i++) { start_time[i] = end_time[i - 1]; end_time[i] = start_time[i] + duration_time[i]; wait_time[i] = start_time[i] - require_time[i]; sum += wait_time[i]; } return (float)(sum / n); } int main() { int task_list = 0; cin >> task_list; vector<int> require_time, duration_time; int time0 = 0, time1 = 0; int temp = task_list; while (temp--) { cin >> time0 >> time1; require_time.push_back(time0); duration_time.push_back(time1); } cout << average_time(require_time, duration_time, task_list) << endl; system("pause"); }
标签:
原文地址:http://www.cnblogs.com/zhizhi25/p/5859786.html