题解:AtCoder AT_awc0100_a Calculating Part-Time Job Pay
【题目来源】
AtCoder:A - Calculating Part-Time Job Pay
【题目描述】
Takahashi worked \(N\) different part-time jobs this month.
The hourly wage of the \(i\)-th job is \(A_i\) yen, and Takahashi worked \(T_i\) hours at that job.
Find the total salary (in yen) that Takahashi will receive this month.
高橋这个月做了 \(N\) 份不同的兼职工作。
第 \(i\) 份工作的时薪为 \(A_i\) 日元,高橋在该工作了 \(T_i\) 小时。
求高橋这个月将收到的总工资(以日元计)。
【输入】
\(N\)
\(A_1\) \(T_1\)
\(A_2\) \(T_2\)
\(\vdots\)
\(A_N\) \(T_N\)
- The first line contains \(N\), the number of types of part-time jobs.
- The following \(N\) lines contain the information for each job.
- The \((1 + i)\)-th line contains \(A_i\), the hourly wage of the \(i\)-th job, and \(T_i\), the number of hours worked, separated by a space.
【输出】
Print the total salary (in yen) that Takahashi will receive, on a single line.
【输入样例】
3
1000 5
1200 3
900 4
【输出样例】
12200
【核心思想】
-
问题分析:给定 \(N\) 份兼职工作,第 \(i\) 份时薪为 \(A_i\) 日元,工作时长为 \(T_i\) 小时。求总工资。这是一个直接累加模拟问题,关键在于将每份工作的工资(时薪 \(\times\) 时长)累加得到总和。
-
算法选择:
- 直接模拟(线性累加):遍历每份工作,计算 \(A_i \times T_i\) 并累加到总工资
- 防溢出处理:使用
long long存储结果,防止 \(A_i \times T_i\) 超出int范围
-
关键步骤:
- 初始化:读入 \(N\),初始化
ans = 0 - 遍历累加(\(i\) 从 \(1\) 到 \(N\)):
- 读入 \(A_i\) 和 \(T_i\)
ans += A_i \times T_i
- 输出 \(ans\)
- 初始化:读入 \(N\),初始化
-
时间/空间复杂度:
- 时间复杂度:\(O(N)\),线性遍历 \(N\) 份工作
- 空间复杂度:\(O(1)\),仅使用常数变量
-
直接模拟的核心思想:
- 问题转化:将"总工资"这一复合概念直接翻译为数学表达式 \(\sum_{i=1}^{N} A_i \times T_i\)
- 累加器模式:用单个变量
ans作为累加器,逐次加入每份工作的贡献,避免存储中间数组 - 数据类型预防:乘法结果可能溢出
int范围(如 \(10^9 \times 10^9 = 10^{18}\)),提前使用long long保证正确性 - 适用于"多组数据线性求和"的基础计算问题
【算法标签】
模拟
【代码详解】
#include <bits/stdc++.h>
using namespace std;
#define int long long // 将 int 宏定义为 long long,防止乘法运算溢出
int n, ans; // n: 兼职工作数量; ans: 累计总工资(初始为0)
signed main() // 使用 signed main 以兼容 #define int long long 的宏定义
{
cin >> n; // 读取工作数量 N
for (int i = 1; i <= n; i++) // 循环遍历每一份工作
{
int a, t; // a: 当前工作的时薪(日元/小时); t: 当前工作的工作时长(小时)
cin >> a >> t; // 读取时薪和工作时长
ans += a * t; // 累加当前工作的工资(时薪 × 时长)到总工资
}
cout << ans << endl; // 输出总工资(日元)
return 0; // 程序正常结束
}
【运行结果】
3
1000 5
1200 3
900 4
12200
浙公网安备 33010602011771号