题目链接
题目描述
小红有 天的工作和直播计划。
对于每一天:
- 她会先上班,每上班 1 小时,焦虑度增加
。
- 下班后她会直播,每直播 1 小时,焦虑度降低
。
初始时,她的焦虑度为 0。需要注意的是,焦虑度最低为 0,不会降到负数。
给定 天里每天的上班和直播时长,求第
天结束时小红的最终焦虑度。
思路分析
这是一个直接的模拟题。我们只需要按照天数顺序,一步步计算焦虑度的变化即可。
1. 维护状态
我们需要一个变量,例如 current_anxiety
,来实时追踪当前的焦虑度。它的初始值为 0。
2. 逐天模拟
我们从第 1 天循环到第 天。在每一天
的循环中,执行以下操作:
-
增加焦虑度:根据当天上班时长
和单位增量
,增加焦虑度。
current_anxiety += work_hours_i * a;
-
降低焦虑度:根据当天直播时长
和单位减量
,计算总共需要降低的焦虑度。
long long decrease_amount = stream_hours_i * b;
-
更新焦虑度(核心):从当前焦虑度中减去要降低的量。由于焦虑度不能为负,所以更新结果需要和 0 取一个最大值。
current_anxiety = max(0LL, current_anxiety - decrease_amount);
(在 C++ 中使用0LL
确保max
函数在long long
类型上操作)。
3. 数据类型
由于天数 和每天的时长、焦虑度变化值可能导致最终的焦虑度累积到一个很大的数值,为了防止整数溢出,应该使用 64 位整型(如 C++ 中的
long long
或 Java 中的 long
)来存储 current_anxiety
。
循环结束后,current_anxiety
的最终值就是答案。
代码
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
int main() {
int n;
long long a, b;
cin >> n >> a >> b;
vector<long long> work_hours(n);
vector<long long> stream_hours(n);
for (int i = 0; i < n; ++i) {
cin >> work_hours[i];
}
for (int i = 0; i < n; ++i) {
cin >> stream_hours[i];
}
long long current_anxiety = 0;
for (int i = 0; i < n; ++i) {
current_anxiety += work_hours[i] * a;
long long decrease_amount = stream_hours[i] * b;
current_anxiety = max(0LL, current_anxiety - decrease_amount);
}
cout << current_anxiety << endl;
return 0;
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long a = sc.nextLong();
long b = sc.nextLong();
long[] workHours = new long[n];
long[] streamHours = new long[n];
for (int i = 0; i < n; i++) {
workHours[i] = sc.nextLong();
}
for (int i = 0; i < n; i++) {
streamHours[i] = sc.nextLong();
}
long currentAnxiety = 0;
for (int i = 0; i < n; i++) {
currentAnxiety += workHours[i] * a;
long decreaseAmount = streamHours[i] * b;
currentAnxiety = Math.max(0L, currentAnxiety - decreaseAmount);
}
System.out.println(currentAnxiety);
}
}
n, a, b = map(int, input().split())
work_hours = list(map(int, input().split()))
stream_hours = list(map(int, input().split()))
current_anxiety = 0
for i in range(n):
current_anxiety += work_hours[i] * a
decrease_amount = stream_hours[i] * b
current_anxiety = max(0, current_anxiety - decrease_amount)
print(current_anxiety)
算法及复杂度
-
算法:模拟
-
时间复杂度:
。
- 我们需要读取
天的数据,并对这
天进行一次遍历,所以时间复杂度是线性的。
- 我们需要读取
-
空间复杂度:
。
- 主要的空间开销是存储
天的上班和直播时长的数组。如果边读边处理,可以将空间复杂度优化到
。
- 主要的空间开销是存储