刚开始学的时候做这题觉得好复杂,时隔这么久回过头来再做这题,思路竟然异常的简单和清晰
P2010 [NOIP 2016 普及组] 回文日期
题目背景
NOIP2016 普及组 T2
题目描述
在日常生活中,通过年、月、日这三个要素可以表示出一个唯一确定的日期。
牛牛习惯用 \(8\) 位数字表示一个日期,其中,前 \(4\) 位代表年份,接下来 \(2\) 位代表月份,最后 \(2\) 位代表日期。显然:一个日期只有一种表示方法,而两个不同的日期的表示方法不会相同。
牛牛认为,一个日期是回文的,当且仅当表示这个日期的 \(8\) 位数字是回文的。现在,牛牛想知道:在他指定的两个日期之间(包含这两个日期本身),有多少个真实存在的日期是回文的。
一个 \(8\) 位数字是回文的,当且仅当对于所有的 \(i\)(\(1 \le i \le 8\))从左向右数的第 \(i\) 个数字和第 \(9-i\) 个数字(即从右向左数的第 \(i\) 个数字)是相同的。
例如:
- 对于 2016 年 11 月 19 日,用 \(8\) 位数字 \(20161119\) 表示,它不是回文的。
- 对于 2010 年 1 月 2 日,用 \(8\) 位数字 \(20100102\) 表示,它是回文的。
- 对于 2010 年 10 月 2 日,用 \(8\) 位数字 \(20101002\) 表示,它不是回文的。
每一年中都有 \(12\) 个月份:
其中,\(1, 3, 5, 7, 8, 10, 12\) 月每个月有 \(31\) 天;\(4, 6, 9, 11\) 月每个月有 \(30\) 天;而对于 \(2\) 月,闰年时有 \(29\) 天,平年时有 \(28\) 天。
一个年份是闰年当且仅当它满足下列两种情况其中的一种:
- 这个年份是 \(4\) 的整数倍,但不是 \(100\) 的整数倍;
- 这个年份是 \(400\) 的整数倍。
例如:
- 以下几个年份都是闰年:\(2000, 2012, 2016\)。
- 以下几个年份是平年:\(1900, 2011, 2014\)。
输入格式
两行,每行包括一个 \(8\) 位数字。
第一行表示牛牛指定的起始日期。
第二行表示牛牛指定的终止日期。
保证 \(\mathit{date}_1\) 和 \(\mathit{date}_2\) 都是真实存在的日期,且年份部分一定为 \(4\) 位数字,且首位数字不为 \(0\)。
保证 \(\mathit{date}_1\) 一定不晚于 \(\mathit{date}_2\)。
输出格式
一个整数,表示在 \(\mathit{date}_1\) 和 \(\mathit{date}_2\) 之间,有多少个日期是回文的。
输入输出样例 #1
输入 #1
20110101
20111231
输出 #1
1
输入输出样例 #2
输入 #2
20000101
20101231
输出 #2
2
说明/提示
【样例说明】
对于样例 1,符合条件的日期是 \(20111102\)。
对于样例 2,符合条件的日期是 \(20011002\) 和 \(20100102\)。
【子任务】
对于 \(60 \%\) 的数据,满足 \(\mathit{date}_1 = \mathit{date}_2\)。
AC代码
#include<bits/stdc++.h>
using namespace std;
int day[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
char a[9],b[9];bool isrun(int x){if((x%4==0&&x%100!=0)||x%400==0) return true;return false;
}int trans(char a[]){int ans=0;for(int i=0;i<8;i++){ans=10*ans+int(a[i]-'0');}return ans;
}bool ishui(int x){int p=1e7;for(int i=0;i<4;i++){if(x/p!=x%10) return false;x=x%p;x=x/10;p=p/100;}return true;
}int main(){cin>>a>>b;int da=trans(a);int db=trans(b);int ayear=da/10000,byear=db/10000,amon=(da/100)%100,bmon=(db/100)%100,aday=da%100,bday=db%100;int flag1,flag2,flag3,flag4;int cnt=0;for(int year=ayear;year<=byear;year++){flag1=flag2=0;if(year==ayear) flag1=1;if(year==byear) flag2=1;for(int mon=(flag1==1?amon:1);mon<=(flag2==1?bmon:12);mon++){int t=day[mon];flag3=flag4=0;if(mon==amon&&flag1) flag3=1;if(mon==bmon&&flag2) flag4=1;if(isrun(year)&&mon==2) t=29; for(int day=(flag3==1?aday:1);day<=(flag4==1?bday:t);day++){if(ishui(year*10000+mon*100+day)) cnt++;}}}cout<<cnt<<endl;return 0;
}