回文日期
超时了,只过了90%的数据
#include<iostream>
#include<cstring>
#include<sstream>
using namespace std;
string data1;
string data2;
int cnt;
int y1,m1,d1;
int y2,m2,d2;
int day[] = {31,28,31,30,31,30,31,31,30,31,30,31};
bool check(string s)
{
int i=0, j=s.size()-1;
while(i<j)
{
if(s[i]!=s[j]) return false;
i++; j--;
}
return true;
}
void digitalize()
{
y1 = stoi(data1.substr(0,4));
m1 = stoi(data1.substr(4,2));
d1 = stoi(data1.substr(6,2));
y2 = stoi(data2.substr(0,4));
m2 = stoi(data2.substr(4,2));
d2 = stoi(data2.substr(6,2));
}
void addoneday()
{
int flag = 0; // 判断是否是闰年
if(y1%400==0 || ((y1%4)==0&&(y1%100)!=0)) flag = 1;
if(flag && m1==2)
{
if(d1==29)
{
m1=3;
d1=1;
}else
d1++;
}else
{
if(d1==day[m1-1])
{
d1=1;
m1++;
if(m1==13) {m1=1; y1++;}
}else
d1++;
}
}
int main()
{
cin >> data1;
cin >> data2;
digitalize();
int k =0;
while(1)
{
if(y1==y2&&m1==m2&&d1==d2) break;
string s = to_string(y1);
if(m1<10) s = s + "0" + to_string(m1);
else s = s + to_string(m1);
if(d1<10) s = s + "0" + to_string(d1);
else s = s + to_string(d1);
if(check(s)) cnt++;
addoneday();
}
if(check(data2)) cnt++;
cout << cnt << endl;
return 0;
}
能过全部数据
#include<iostream>
#include<cstring>
#include<sstream>
using namespace std;
string data1;
string data2;
int cnt;
int y1,m1,d1;
int y2,m2,d2;
int day[] = {31,28,31,30,31,30,31,31,30,31,30,31};
bool check(string s)
{
int i=0, j=s.size()-1;
while(i<j)
{
if(s[i]!=s[j]) return false;
i++; j--;
}
return true;
}
void digitalize()
{
y1 = stoi(data1.substr(0,4));
m1 = stoi(data1.substr(4,2));
d1 = stoi(data1.substr(6,2));
y2 = stoi(data2.substr(0,4));
m2 = stoi(data2.substr(4,2));
d2 = stoi(data2.substr(6,2));
}
void addoneday()
{
int flag = 0; // 判断是否是闰年
if(y1%400==0 || ((y1%4)==0&&(y1%100)!=0)) flag = 1;
if(flag && m1==2)
{
if(d1==29)
{
m1=3;
d1=1;
}else
d1++;
}else
{
if(d1==day[m1-1])
{
d1=1;
m1++;
if(m1==13) {m1=1; y1++;}
}else
d1++;
}
}
int main()
{
cin >> data1;
cin >> data2;
digitalize();
int k =0;
while(1)
{
if(y1>y2) break;
int st = y1%10*10 + y1%100/10;
if(st==0||st>12) {y1++;m1=1;d1=1;continue;} //年份
if(m1<st) {m1=st;d1=1;} // 月份
if(m1>st) {y1++;continue;}
if(y1==y2 && (m1>m2||(m1==m2&&d1>=d2))) break;
string s = to_string(y1);
if(m1<10) s = s + "0" + to_string(m1);
else s = s + to_string(m1);
if(d1<10) s = s + "0" + to_string(d1);
else s = s + to_string(d1);
if(check(s)) cnt++;
addoneday();
}
if(check(data2)) cnt++;
cout << cnt << endl;
return 0;
}
分析:
就纯思路题
分析做了这么久原因:
总计一个小时20分钟,太慢了,我其他题还做不做了QAQ。主要是to_string、stdoi不熟,就字符串和数字转换不熟,然后思路不清晰,最开始一天一天加,超时了,然后再观察发现因为回文,所以年份确定,所以月份也就确定,是年份后两位的倒数,实际还可以更简单因为这样只有10 20 30 40…这几个特定年份有回文。但我看过了90%,估计时间卡得不紧,就直接在原来代码改了下,然后边界条件有时调试了20分钟…