466. 回文日期
题目链接
466. 回文日期
在日常生活中,通过年、月、日这三个要素可以表示出一个唯一确定的日期。
牛牛习惯用 \(8\) 位数字表示一个日期,其中,前 \(4\) 位代表年份,接下来 \(2\) 位代表月份,最后 \(2\) 位代表日期。
显然:一个日期只有一种表示方法,而两个不同的日期的表示方法不会相同。
牛牛认为,一个日期是回文的,当且仅当表示这个日期的 \(8\) 位数字是回文的。
现在,牛牛想知道:在他指定的两个日期之间(包含这两个日期本身),有多少个真实存在的日期是回文的。
一个 \(8\) 位数字是回文的,当且仅当对于所有的 \(i(1≤i≤8)\) 从左向右数的第 \(i\) 个数字和第 \(9−i\) 个数字(即从右向左数的第 \(i\) 个数字)是相同的。
例如:
对于 \(2016\) 年 \(11\) 月 \(19\) 日,用 \(8\) 位数字 \(20161119\) 表示,它不是回文的。
对于 \(2010\) 年 \(1\) 月 \(2\) 日,用 \(8\) 位数字 \(20100102\) 表示,它是回文的。
对于 \(2010\) 年 \(10\) 月 \(2\) 日,用 \(8\) 位数字 \(20101002\) 表示,它不是回文的。
输入格式
输入包括两行,每行包括一个 \(8\) 位数字。
第一行表示牛牛指定的起始日期 \(date1\),第二行表示牛牛指定的终止日期 \(date2\)。保证 \(date1\) 和 \(date2\) 都是真实存在的日期,且年份部分一定为 \(4\) 位数字,且首位数字不为 \(0\)。
保证 \(date1\) 一定不晚于 \(date2\)。
输出格式
输出共一行,包含一个整数,表示在 \(date1\) 和 \(date2\) 之间,有多少个日期是回文的。
输入样例:
20110101
20111231
输出样例:
1
解题思路
模拟
从 \(1000\) 到 \(9999\) 模拟年份,构造回文日期,判断其是否满足日期的格式且在范围即可,注意闰年二月份为 \(29\) 天
- 时间复杂度:\(O(10000)\)
代码
// Problem: 回文日期
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/468/
// Memory Limit: 64 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)
// %%%Skyqwq
#include <bits/stdc++.h>
#define pb push_back
#define fi first
#define se second
#define mkp make_pair
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; }
template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; }
template <typename T> void inline read(T &x) {
int f = 1; x = 0; char s = getchar();
while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
x *= f;
}
int date1,date2;
int months[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
bool ck(int x)
{
int year=x/10000,month=x/100%100,day=x%100;
if(!month||month>=13)return false;
if(month!=2&&(!day||day>months[month]))return false;
if(month==2&&((year%100!=0&&year%4==0||year%400==0)+28)<day)return false;
return true;
}
int main()
{
cin>>date1>>date2;
int res;
for(int i=1000;i<10000;i++)
{
int date=i,t=i;
for(int j=0;j<4;j++)date=date*10+t%10,t/=10;
if(ck(date)&&date>=date1&&date<=date2)res++;
}
cout<<res;
return 0;
}