题目描述
小明正在整理一批历史文献。这些历史文献中出现了很多日期。
小明知道这些日期都在1960年1月1日至2059年12月31日。
令小明头疼的是,这些日期采用的格式非常不统一,有采用年/月/日的,有采用月/日/年的,还有采用日/月/年的。
更加麻烦的是,年份也都省略了前两位,使得文献上的一个日期,存在很多可能的日期与其对应。
比如02/03/04,可能是2002年03月04日、2004年02月03日或2004年03月02日。
给出一个文献上的日期,你能帮助小明判断有哪些可能的日期对其对应吗?
输入格式
一个日期,格式是”AA/BB/CC”。
即每个’/’隔开的部分由两个 0-9 之间的数字(不一定相同)组成。
输出格式
输出若干个不相同的日期,每个日期一行,格式是”yyyy-MM-dd”。
多个日期按从早到晚排列。
数据范围
0≤A,B,C≤9
输入样例:
02/03/04
输出样例:
2002-03-04
2004-02-03
2004-03-02
算法1 (小白模拟 非常的笨重见笑了)
C++ 代码
#include<iostream>
#include<string.h>
#include<cstdio>
#include<algorithm>
#include<set>
using namespace std;
const int N=10;
string str;
int date[3],ans[3];
int months[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
bool check(int year1,int month,int day){
if(!year1||!month ||!day) return false;
if(month<0 || month>13 ) return false;
if(month!=2 && day>months[month]) return false;
if(month==2){
bool leap=((year1%4==0) && (year1%100!=0) || year1%400==0);
if(day>(months[month]+leap)) return false; //注意
}
return true;
}
int main(){
cin>>str;
date[0] = (str[0] - '0') * 10 + str[1] - '0';
date[1] = (str[3] - '0') * 10 + str[4] - '0';
date[2] = (str[6] - '0') * 10 + str[7] - '0';
//第一种情况年月日
int year[2];
year[0]=(19*100+date[0]),year[1]=(20*100+date[0]);
for(int i=0;i<2;i++){
if(year[i]>=1960 &&year[i]<=2059){
if(check(year[i],date[1],date[2])) {
// cout<<year[i]<<"-"<<str[3]<<str[4]<<"-"<<str[6]<<str[7]<<endl;
ans[0]=year[i]*10000+date[1]*100+date[2];
}
}
}
//第二种情况 月/日/年
int year1[2];
year1[0]=(19*100+date[2]),year1[1]=(20*100+date[2]);
for(int i=0;i<2;i++){
if(year1[i]>=1960 &&year1[i]<=2059){
if(check(year1[i],date[0],date[1])) {
// cout<<year1[i]<<"-"<<str[0]<<str[1]<<"-"<<str[3]<<str[4]<<endl;
ans[1]=year1[i]*10000+date[0]*100+date[1];
}
}
}
//第三种情况 日/月/年
int year2[2];
year2[0]=(19*100+date[2]),year2[1]=(20*100+date[2]);
for(int i=0;i<2;i++){
if(year2[i]>=1960 &&year2[i]<=2059){
if(check(year2[i],date[1],date[0])) {
// cout<<year2[i]<<"-"<<str[3]<<str[4]<<"-"<<str[0]<<str[1]<<endl;
ans[2]=year2[i]*10000+date[1]*100+date[0];
}
}
}
sort(ans,ans+3); //排序
int cnt=0,num[3];
//去重
for(int i=0;i<3;i++){
if(!ans[i] || ans[i]==ans[i+1]){
continue;
}
else num[cnt++]=ans[i];
}
//打印
for(int i=0;i<cnt;i++) {
int year=num[i]/10000;
int month=num[i]%10000/100;
int day=num[i]%100;
if(month<10 && day<10){
cout<<year<<"-"<<"0"<<month<<"-"<<"0"<<day<<endl;
}
else if(month<10 ){
cout<<year<<"-"<<"0"<<month<<"-"<<day<<endl;
}
else if(day<10){
cout<<year<<"-"<<month<<"-"<<"0"<<day<<endl;
}
else cout<<year<<"-"<<month<<"-"<<day<<endl;
}
return 0;
}