a180簡單流程模擬、時間與狀態更新
TOI 2021/10 新手組:電梯
從 1 樓出發,逐段依上升或下降計算耗電。
這題在學什麼
current 初始為 1;依序讀取下一個樓層 x,用差值 x-current 判斷方向。
差值非負時加上差值的 3 倍,負值時加上下降層數的 2 倍;同樓層加 0。
每段結束都把 current 更新成 x,不能全部都跟 1 樓比較。
Step-by-step animation
電梯・逐段累計耗電
步驟 1 / 3
起始與上升
從 1 到 3 再到 7,耗電 6+12。
1→3
3→7
- energy
- 18
- current
- 7
#include <iostream>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, cur = 1;
cin >> n;
long long ans = 0;
for (int i = 0, x; i < n; i++) {
cin >> x;
ans += (x >= cur ? 3LL * (x - cur) : 2LL * (cur - x));
cur = x;
}
cout << ans << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。