时间回文——有限制的枚举
回文日期
https://www.acwing.com/problem/content/468/
视频:https://www.acwing.com/video/646/
分析
又是一道枚举题,看题目,给出起始和截止的两个八位数,求出处于该范围内的回文数字。
看一下时间复杂度:最多需要遍历1e8个数字,所以算法只能限制在o(n)级别,对于暴力算法是肯定行不通的,因为至少是4*1e9的时间复杂度。因此, 需要换一个思路.
先确定日期
因为是日期,所以月和日是有限制的,先枚举一下日和月,然后通过日和月,算出年,组合起来,看是否在要求的范围内,由于月份有12个日期至多有31个,所以12 * 31 = 372,初步分析是不会TLE的
#include<iostream>
using namespace std;
int days[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int main()
{
int be, en;
cin >> be >> en;
int ans = 0;
for(int i = 1; i < 13; i ++)
for(int j = 1; j <= days[i]; j ++)
{
int year = j % 10 * 1000 + j / 10 * 100 + i % 10 * 10 + i / 10;
year = year * 10000 + i * 100 + j;
if(year >= be && year <= en)
ans ++;
}
cout << ans;
return 0;
}
先确定年份
#include<iostream>
using namespace std;
int days[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int main()
{
int be, en;
cin >> be >> en;
int bey = be / 10000, eny = en / 10000;
int ans = 0;
for(int res = bey; res <= eny; res ++)
{
int day = res / 1000 + (res / 100) % 10 * 10;
int month = (res / 10) % 10 + res % 10 * 10;
if(month && month < 13 && day <= days[month] && day)
{
int date = res * 10000 + month * 100 + day;
if(date <= en && date >= be)ans ++;
}
}
cout << ans;
return 0;
}
时间:
两种方法耗时都是22ms左右, 所以说这两种代码的时间复杂度是差不多的

浙公网安备 33010602011771号