题目:一个公司下面有N个部门,现在要给每个部门分配任务,分配任务只能按照分配的顺序进行,不能同时分配两个任务,只能一个接一个的分配,但是分配完任务后,该部门可以立刻执行(不间断)。分配一个任务的时间是a,执行的时间是b。你需要做的就是决定分配给每一个部门任务的顺序,使得所有部门完成任务的总时间最短。
例子1
输入
3 (代表3个部门)
2 2
3 4
1 5 (第一组数据,前面为分配时间,后面为执行时间)
输出: 8
例子2:
2 4
4 2
3 3
输出 :11
该算法的思路是贪心算法,将部门按照执行时间从大到小排序,然后按照排序后的顺序依次分配任务,并记录当前的时间。每次分配任务时,将当前时间加上该部门的分配时间,并与该部门的执行时间相加,得到该部门完成任务所需的总时间。记录所有部门完成任务所需的总时间,最后输出最大的完成时间即可。
如有错误,请指正。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Department {
int allocation_time; // 分配时间
int execution_time; // 执行时间
};
bool compare(const Department& a, const Department& b) {
return a.execution_time > b.execution_time;
}
int main() {
int n;
cin >> n;
vector<Department> departments(n);
for (int i = 0; i < n; i++) {
cin >> departments[i].allocation_time >> departments[i].execution_time;
}
sort(departments.begin(), departments.end(), compare);
int current_time = 0;
int total_time = 0;
for (int i = 0; i < n; i++) {
current_time += departments[i].allocation_time;
total_time = max(total_time, current_time + departments[i].execution_time);
}
cout << total_time << endl;
return 0;
}