日期問題
原題目鏈接
題目描述
小明正在整理一批歷史文獻。這些歷史文獻中出現了很多日期。
小明知道這些日期都在 1960 年 1 月 1 日 至 2059 年 12 月 31 日 之間。
令小明頭疼的是,這些日期采用的格式非常不統一:
- 有的采用 年/月/日
- 有的采用 月/日/年
- 有的采用 日/月/年
更加麻煩的是,年份省略了前兩位,例如:
02/03/04
它可能表示以下三種日期:
- 2002 年 03 月 04 日 (年/月/日)
- 2004 年 02 月 03 日 (日/月/年)
- 2004 年 03 月 02 日 (月/日/年)
輸入描述
一個日期字符串,格式為 AA/BB/CC
,其中 0 ≤ A, B, C ≤ 9
,即每個字段均為兩位數字。
輸出描述
輸出若干個不相同的有效日期(在 1960-01-01
到 2059-12-31
范圍內),每個日期一行,格式為:
yyyy-MM-dd
多個日期按從早到晚的時間順序輸出。
輸入樣例
02/03/04
輸出樣例
2002-03-04
2004-02-03
2004-03-02
c++代碼
#include<bits/stdc++.h>using namespace std;int arr[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
unordered_set<string> st;void valid(string a, string b, string c) {string d = "19";d += a;int year = stoi(d), key = 0, month = stoi(b), day = stoi(c);if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) key = 1;arr[2] += key;if (year >= 1960 && year <= 2059 &&month >= 1 && month <= 12 &&day >= 1 && day <= arr[month] &&st.find(d + "-" + b + "-" + c) == st.end()) st.insert(d + "-" + b + "-" + c);arr[2] -= key;d = "20", d += a, key = 0, year = stoi(d);if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) key = 1;arr[2] += key;if (year >= 1960 && year <= 2059 &&month >= 1 && month <= 12 &&day >= 1 && day <= arr[month] &&st.find(d + "-" + b + "-" + c) == st.end()) st.insert(d + "-" + b + "-" + c);arr[2] -= key;
}int main() {string str, a, b, c;cin >> str;a = str.substr(0, 2), b = str.substr(3, 2), c = str.substr(6, 2);valid(a, b, c), valid(c, a, b), valid(c, b, a);vector<string> ans;for (string s : st) ans.push_back(s);sort(ans.begin(), ans.end());for (string s : ans) cout << s << endl;return 0;
}//by wqs
算法解析
注意這題需要判斷閏年,然后就是暴力模擬就行了。