解题思路
这是一个贪心算法问题。具体要求:
- 有
条鱼需要煎
- 煎锅每次可以同时煎
条鱼
- 每条鱼需要煎两面,每面需要
分钟
- 求煎完所有鱼的最少时间
解决方案:
- 当
时,只需
分钟(所有鱼一起煎,翻面一次)
- 当
时,需要分批煎:
- 如果
能被
整除,需要
分钟
- 如果余数
,可以在最后一批的第一面同时煎完
- 否则需要额外两次翻面
- 如果
代码
#include <iostream>
using namespace std;
class Solution {
public:
int getMinutes(int n, int m) {
if (m >= n) {
return 2; // 一次性煎完所有鱼
}
int batches = n / m; // 完整的批次数
int remainder = n % m; // 剩余的鱼数
if (remainder == 0) {
return batches * 2; // 每批需要2分钟
} else if (remainder <= m/2) {
return batches * 2 + 1; // 最后一批可以优化
} else {
return batches * 2 + 2; // 最后一批需要完整两面
}
}
};
int main() {
int n, m;
Solution solution;
while (cin >> n >> m) {
cout << solution.getMinutes(n, m) << endl;
}
return 0;
}
import java.util.Scanner;
public class Main {
static class Solution {
public int getMinutes(int n, int m) {
if (m >= n) {
return 2; // 一次性煎完所有鱼
}
int batches = n / m; // 完整的批次数
int remainder = n % m; // 剩余的鱼数
if (remainder == 0) {
return batches * 2; // 每批需要2分钟
} else if (remainder <= m/2) {
return batches * 2 + 1; // 最后一批可以优化
} else {
return batches * 2 + 2; // 最后一批需要完整两面
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Solution solution = new Solution();
while (sc.hasNext()) {
int n = sc.nextInt();
int m = sc.nextInt();
System.out.println(solution.getMinutes(n, m));
}
}
}
class Solution:
def get_minutes(self, n: int, m: int) -> int:
if m >= n:
return 2 # 一次性煎完所有鱼
batches = n // m # 完整的批次数
remainder = n % m # 剩余的鱼数
if remainder == 0:
return batches * 2 # 每批需要2分钟
elif remainder <= m//2:
return batches * 2 + 1 # 最后一批可以优化
else:
return batches * 2 + 2 # 最后一批需要完整两面
def main():
while True:
try:
n, m = map(int, input().split())
solution = Solution()
print(solution.get_minutes(n, m))
except EOFError:
break
if __name__ == "__main__":
main()
算法及复杂度
- 算法:贪心算法
- 时间复杂度:
- 只需要简单的数学计算
- 空间复杂度:
- 只需要常数空间