萌新的蓝桥杯题解
第一次直接暴力枚举所有回文日期进行日期判断,结果部分案例没通过
代码1
#include<iostream>
#include<cstring>
using namespace std;
int months[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
bool check( ll date)//判断日期合法性
{
int year = date / 10000; //年
int month = date % 10000 / 100; //月
int day = date % 100; //日
if(!month || month > 12 || !day ) return false;//如果月份大于12或者为零或者天数为零则该日期不合法
if(month != 2 && day > months[month]) return false;//在不是二月的情况下,该月实际天数大于该月最大天数,则该日期不合法
if(month == 2) //特判二月
{
if((year % 4 == 0&& year % 100 != 0) || (year % 400 == 0))//特判闰年
{
if(day > 29) return false;
}
else if( day > 28) return false;
}
return true;
}
bool f1(string x){//判断回文
for(int i=0;i<8;i++){
if(x[i]!=x[7-i]) return false;
}
return true;
}
bool f2(string x){//判断是否为 ABABBABA
if(x[0]==x[2]&&x[0]==x[5]&&x[0]==x[7]&&x[1]==x[3]&&x[1]==x[4]&&x[1]==x[6]&&x[0]!=x[1]) return true;
else return false;
}
int main(){
cin>>n;//输入起始日期
int idx=0;
for( ll i=n+1;i<=89991231;i++){
if(check(i)){//判断日期合法性
string s=to_string(i);//转换字符串
if(f1(s)){//判断回文
idx++;
if(idx==1) cout<<s<<endl;//判断是否为第一个回文串
if(f2(s)){//判断是否满足ABABBABA
cout<<s;
break;
}
}
}
}
return 0;
}
第二次尝试利用字符串
枚举年份 y,再用reverse将其翻转得到 y’,那么 y+y’ 就是一个回文串。再对该串所对应的日期进行合法判断、 ABABBABA 型回文判断。
代码2
#include<bits/stdc++.h>
using namespace std;
int months[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
bool check( string x)//判断日期合法性
{
int year = stoi(x.substr(0,4)); //年
int month =stoi(x.substr(4,2)); //月
int day = stoi(x.substr(6,2)); //日
if(!month || month > 12 || !day ) return false;//如果月份大于12或者为零或者天数为零则该日期不合法
if(month != 2 && day > months[month]) return false;//在不是二月的情况下,该月实际天数大于该月最大天数,则该日期不合法
if(month == 2) //特判二月
{
if((year % 4 == 0&& year % 100 != 0) || (year % 400 == 0))//特判闰年
{
if(day > 29) return false;
}
else if( day > 28) return false;
}
return true;
}
bool ok(string x){//判断是否为 ABABBABA回文串
if(x[0]==x[2]&&x[0]==x[5]&&x[0]==x[7]&&x[1]==x[3]&&x[1]==x[4]&&x[1]==x[6]&&x[0]!=x[1]) return true;
else return false;
}
int main(){
string s;
cin>>s;
int idx=0;
for(int i=stoi(s.substr(0,4));;i++){
string s1=to_string(i),s2=to_string(i);
reverse(s2.begin(),s2.end());
s1+=s2;
if(check(s1)&&s1>s&&idx==0){
cout<<s1<<endl;
idx++;
}
if(check(s1)&&s1>s&&ok(s1)){
cout<<s1;
break;
}
}
return 0;
}