题目描述
现有训练子任务模型的列表tasks, tasks[i]表示第i个子任务的算力需求,为了保证模型计算的时间,要求所有任务在T时刻内完成计算。
每个时刻,需要按照给出子任务模型的算力需求列表调度到量子计算机完成计算,任意时刻调度的多个子任务的算力需求综合不能超过量子计算机的最大算力负荷。
请返回量子计算机所需要提供的最低算力,可以在T时刻内计算完全部子任务模型。
输入描述
输入:包含两行,第一行2个整数N, T,分别表示子任务模型列表长度,计算子任务模型的时刻要求。
第二行包含N个整数:task[1] task[2] task[3] … task[n]分别表示第i个子任务的算力需求。
输出描述
输出:一行包含一个整数,表示量子计算机所需要的最低算力。
用例输入
10 5
1 2 3 4 5 6 7 8 9 10
15
解题思路
使用二分查找来确定量子计算机所需要的最低算力。首先,确定算力的可能范围,最小值为所有子任务中最大的算力需求,最大值为所有子任务的算力需求之和。然后,通过二分查找来确定在给定的时刻T内,量子计算机能够完成所有任务的最低算力。
代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include<algorithm>
#include<string>
#include<vector>
#include<unordered_map>
#include<unordered_set>
#include<queue>
#include<set>
#include<list>
#include<sstream>
#include<bitset>
#include<stack>
#include<climits>
#include<iomanip>
#include<cstdint>
using namespace std;
// 检查在给定的算力r下,是否可以在T时刻内完成所有任务
bool check(vector<int>& datas, int t, int r) {
int cur = 0;
int res = 0;
for (int i = 0; i < datas.size(); i++) {
if (cur + datas[i] > r) {
res++;
cur = datas[i];
}
else {
cur += datas[i];
}
}
res++;
return res <= t;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
// 二分查找,要求的是按照顺序 所有不排序
int n, t;
int l = 0, r = 0;
cin >> n >> t;
vector<int> datas(n);
for (int i = 0; i < n; i++) {
cin >> datas[i];
r += datas[i];
l = max(l, datas[i]);
}
int res = r;
while (l <= r) {
int mid = (l + r) / 2;
if (check(datas, t, mid)) {
res = mid;
r = mid - 1;
}
else {
l = mid + 1;
}
}
cout << res << endl;
}