OD统一考试(C卷)
分值: 100分
题解: Java / Python / C++
题目描述
为了充分发挥GPU算力,需要尽可能多的将任务交给GPU执行,现在有一个任务数组,数组元素表示在这1秒内新增的任务个数且每秒都有新增任务。
假设GPU最多一次执行n个任务,一次执行耗时1秒,在保证GPU不空闲情况下,最少需要多长时间执行完成。
输入描述
第一个参数为GPU一次最多执行的任务个数,取值范围[1, 10000]
第二个参数为任务数组长度,取值范围[1, 10000]
第三个参数为任务数组,数字范围[1, 10000]
输出描述
执行完所有任务最少需要多少秒。
示例1
输入:
3
5
1 2 3 4 5
输出:
6
说明:
一次最多执行 3 个任务,最少耗时 6s。
示例2
输入:
4
5
5 4 1 1 1
输出:
5
说明:
一次最多执行 4 个任务,最少耗时 5s。
题解
这个问题可以使用贪心策略来解决。
主要思路是遍历任务数组,每秒执行尽可能多的任务,然后根据剩余任务数量计算等待时间。
Java
java">import java.util.Scanner;
/**
* @author code5bug
*/
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 最多一次执行任务数, 任务长度
int n = scanner.nextInt(), taskLength = scanner.nextInt();
// 任务列表
int[] tasks = new int[taskLength];
for (int i = 0; i < taskLength; i++) {
tasks[i] = scanner.nextInt();
}
// 等待的任务数量
int waitNum = 0;
for (int taskNum : tasks) {
// 每秒最多n个任务,执行不完则等待后续执行
waitNum = Math.max(0, waitNum + taskNum - n);
}
// 计算任务执行完成
// (waitNum + n - 1) / n 向上取整
int costTime = taskLength + (waitNum + n - 1) / n;
System.out.println(costTime);
}
}
Python
python"># 最多一次执行任务数
n = int(input())
task_length = int(input())
tasks = list(map(int, input().split()))
# 等待的任务数量
wait_num = 0
for task_num in tasks:
# 每秒最多n个任务, 执行不完则等待后续执行
wait_num = max(0, wait_num + task_num - n)
# 计算任务执行完成
# (wait_num + n - 1) // n 向上取整的写法
cost_time = task_length + (wait_num + n - 1) // n
print(cost_time)
C++
#include <iostream>
#include <vector>
using namespace std;
int main() {
// 最多一次执行任务数, 任务长度
int n, taskLength;
cin >> n >> taskLength;
// 任务列表
vector<int> tasks(taskLength);
for (int i = 0; i < taskLength; i++) {
cin >> tasks[i];
}
// 等待的任务数量
int waitNum = 0;
for (int taskNum : tasks) {
// 每秒最多n个任务,执行不完则等待后续执行
waitNum = max(0, waitNum + taskNum - n);
}
// 计算任务执行完成
int costTime = taskLength + (waitNum + n - 1) / n;
cout << costTime << endl;
return 0;
}
🙏整理题解不易, 如果有帮助到您,请给点个赞 ❤️ 和收藏 ⭐,让更多的人看到。🙏🙏🙏