给定一个字符数组tasks,表示 CPU 需要执行的任务列表。每个任务可以用一个大写字母表示。任务可以按任意顺序执行,且每个任务可以在 1 个单位时间内执行完。
两个相同种类的任务之间必须有长度为n的冷却时间。请计算完成所有任务所需的最短时间。
输入描述
第一行输入一个字符串tasks,表示任务列表。
第二行输入一个整数n,表示冷却时间。
输出描述
输出完成所有任务所需的最短时间。
示例 1
输入
text
AAABBB 2
输出
text
8
说明
一种可行安排:A -> B -> idle -> A -> B -> idle -> A -> B,共 8 个单位时间。
C++ 解法
cpp
#include <bits/stdc++.h> using namespace std; int main() { string tasks; cin >> tasks; int n; cin >> n; vector<int> cnt(26, 0); for (char c : tasks) cnt[c - 'A']++; sort(cnt.begin(), cnt.end(), greater<int>()); int maxCount = cnt[0]; int maxCountNum = 0; for (int x : cnt) { if (x == maxCount) maxCountNum++; } int ans = (maxCount - 1) * (n + 1) + maxCountNum; cout << max(ans, (int)tasks.size()) << endl; return 0; }