神奇苹果桶
[题目链接](https://www.nowcoder.com/practice/dec56cf338154d30bd0f56b30ee8769a)
思路
本题是一道简单的模拟题。维护一个变量 apples 表示当前苹果数量(初始为 0),依次处理 次操作:
- 操作 1(增加):
apples += x - 操作 2(取走):若
apples >= x,则apples -= x,否则不操作 - 操作 3(按比例取走):取走
个苹果,即
apples -= ceil(apples / x)
对于向上取整,可以利用整数运算公式 来避免浮点数精度问题。
注意苹果数量可能较大,需要使用 long long(C++)或 long(Java)。
复杂度
- 时间复杂度:
,每次操作
- 空间复杂度:
代码
[sol-C++]
#include <iostream>
using namespace std;
int main() {
int n;
scanf("%d", &n);
long long apples = 0;
for (int i = 0; i < n; i++) {
int op;
long long x;
scanf("%d %lld", &op, &x);
if (op == 1) {
apples += x;
} else if (op == 2) {
if (apples >= x) {
apples -= x;
}
} else {
long long take = (apples + x - 1) / x;
apples -= take;
}
}
printf("%lld\n", apples);
return 0;
}
[sol-Java]
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long apples = 0;
for (int i = 0; i < n; i++) {
int op = sc.nextInt();
long x = sc.nextLong();
if (op == 1) {
apples += x;
} else if (op == 2) {
if (apples >= x) {
apples -= x;
}
} else {
long take = (apples + x - 1) / x;
apples -= take;
}
}
System.out.println(apples);
}
}

京公网安备 11010502036488号