1 条题解
-
0
练25.2 订餐时间
解题思路
按顺序到店时,全部旅行时间就是相邻路段耗时之和。读入 n 个时间并累加,不需要计算回家路程。
正确性说明
按上述推导执行:每次仅处理当前输入或当前步骤,并把它对答案的贡献计入对应状态。所有需要处理的情况均被覆盖,结束时保存的量就是题目所求。
易错点
最后到第 n 家即结束,不额外加返回路程。
复杂度
时间 O(n),额外空间 O(1)。
参考代码(C++11)
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; long long sum = 0; for (int i = 0; i < n; i++) { int x; cin >> x; sum += x; } cout << sum << "\n"; return 0; }
- 1