a607中等分鐘區間分類與整數分計費
CPE:Gondwanaland Telecom (UVa 145)
準確處理跨午夜、跨費率與固定欄寬輸出。
解題思路
把時分轉成從午夜起的分鐘。若結束分鐘不大於開始分鐘,就加 1440;相等代表完整 24 小時。枚舉半開區間 [start,end) 的每分鐘,取模 1440 後,以 480、1080、1320 為邊界分成日間、晚間、夜間。
通話最長只有 1440 分鐘,直接逐分分類已足夠快,也能避開跨午夜的分段錯誤。費率用整數分儲存,先算總分再格式化為兩位小數。輸出六欄靠右、寬度 10、6、6、6、3、8,沒有額外分隔符;讀到 # 結束,題敘中的欄位標示數字不輸出。
Step-by-step animation
示意:A 級 17:58 到 18:04
步驟 1 / 3
轉換分鐘
開始 1078,結束 1084,總長 6 分鐘。
1078
1080
1084
- 通話長
- 6
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
int main() {
int rate[5][3] = {{10, 6, 2}, {25, 15, 5}, {53, 33, 13}, {87, 47, 17}, {144, 80, 30}};
string type, phone;
while (cin >> type && type != "#") {
int h1, m1, h2, m2;
cin >> phone >> h1 >> m1 >> h2 >> m2;
int start = h1 * 60 + m1, end = h2 * 60 + m2;
if (end <= start)
end += 1440;
int count[3] = {};
for (int t = start; t < end; ++t) {
int x = t % 1440;
int band = (x >= 480 && x < 1080) ? 0 : (x >= 1080 && x < 1320) ? 1 : 2;
++count[band];
}
int cost = 0;
for (int j = 0; j < 3; ++j)
cost += count[j] * rate[type[0] - 'A'][j];
string money =
to_string(cost / 100) + "." + (cost % 100 < 10 ? "0" : "") + to_string(cost % 100);
cout << setw(10) << phone << setw(6) << count[0] << setw(6) << count[1] << setw(6)
<< count[2] << setw(3) << type << setw(8) << money << '\n';
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。