a553簡單日期字典序與已滿年齡

CPE:How old are you? (UVa 11219)

先判定未來出生,再按今年生日是否已過修正歲數。

前往題目練習 →回報教學錯誤每筆時間 O(1),空間 O(1)。

解題思路

把 DD/MM/YYYY 轉成 (年,月,日),就能依字典序比較兩日期。若出生日期晚於目前日期,直接輸出 Invalid birth date,不能只比較年份,因為同年也可能尚未出生。

其餘先算目前年減出生年,再比較 (目前月,目前日) 是否小於生日月日,尚未到就減1。算完的已滿歲數大於130才是 Check birth date;恰好130仍合法。日期 token 中沒有空白,讀 token 可同時處理題面描述的空白行與範例未附空白行的情況。每筆印 Case #k:。

Step-by-step animation

示意:目前28/02/2005,出生29/02/2004

回報動畫錯誤
步驟 1 / 3

轉換格式

比較年、月、日,不以日優先排序。

目前(2005,2,28)
出生(2004,2,29)
未來出生
0

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <tuple>
#include <functional>
#include <limits>
#include <cstdint>
#include <cctype>
#include <utility>
using namespace std;

array<int, 3> date(string s) {
    int d, m, y;
    char slash;
    istringstream in(s);
    in >> d >> slash >> m >> slash >> y;
    return {y, m, d};
}
int main() {
    int t;
    cin >> t;
    for (int tc = 1; tc <= t; ++tc) {
        string a, b;
        cin >> a >> b;
        auto now = date(a), birth = date(b);
        cout << "Case #" << tc << ": ";
        if (birth > now) {
            cout << "Invalid birth date\n";
            continue;
        }
        int age = now[0] - birth[0] - (make_pair(now[1], now[2]) < make_pair(birth[1], birth[2]));
        if (age > 130)
            cout << "Check birth date\n";
        else
            cout << age << '\n';
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多