前言:
这类问题在蓝桥杯中经常出现,没有固定做法,一般难度不算大,但是要考虑很多细节。一般做法是按照题目要求模拟出来,一般不会涉及最优化问题。DP、贪心、DFS、数据结构通常是用来做最优化的,去优化效率。
小结:筛选出不合格的要比筛选出合格的要容易,一般合格比不合格要求严格。
eg:acWing 1229.日期问题
(1)反推法:通过大部分测试点的答案如下,未ac原因:考虑不周全。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=9;
struct Date
{
int b1,b2,b3;
bool operator <(const Date & t)
{
if(b1!=t.b1) return b1<t.b1;
else
{
if(b2!=t.b2) return b2<t.b2;
else{
return b3<t.b3;
}
}
}
};
char s[N];
Date date[3];
int b1,b2,b3;
int days[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
bool check(int y,int m,int d)
{
if(m>12) return false;
if(m!=2&&d>days[m]||d==0) return false;
if(m==2)
{
bool k=y%4==0&&y%100||y%400==0;
if(d>28+k) return false;
}
return true;
}
int main()
{
cin>>s;
b1=(s[0]-'0')*10+s[1]-'0';
b2=(s[3]-'0')*10+s[4]-'0';
b3=(s[6]-'0')*10+s[7]-'0';
date[0].b1=b1,date[0].b2=b2,date[0].b3=b3;
date[1].b1=b3,date[1].b2=b1,date[1].b3=b2;
date[2].b1=b3,date[2].b2=b2,date[2].b3=b1;
sort(date,date+3);
for(int i=0;i<3;i++)
{
b1=date[i].b1;
b2=date[i].b2;
b3=date[i].b3;
if(check(b1,b2,b3))
{
if(b1>=60&&b1<=99&&b1>9)
cout<<"19"<<b1<<"-";
else if(b1>=60&&b1<=99&&b1<10)
cout<<"190"<<b1<<"-";
else if(b1>=0&b1<=59&&b1>9)
cout<<"20"<<b1<<"-";
else if(b1>=0&&b1<=59&&b1<10)
cout<<"200"<<b1<<"-";
if(b2<10)
cout<<"0"<<b2<<"-";
else cout<<b2<<"-";
if(b3<10)
cout<<"0"<<b3<<endl;
else cout<<b3<<endl;
}
}
return 0;
}
(2)正推法:建议用这种方法,列举所有可能答案,然后排除。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int days[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
bool check(int year,int month,int day)
{
if(month==0||month>12) return false;
if(day==0) return false;
if(month!=2)
{
if(day>days[month]) return false;
}
else
{
int k=year%100&&year%4==0||year%400==0;
if(day>28+k) return false;
}
return true;
}
int main()
{
int a,b,c;
scanf("%d/%d/%d",&a,&b,&c);
for(int i=19600101;i<=20591231;i++)
{
int year=i/10000,month =i%10000/100,day=i%100;
if(check(year,month,day))
{
if(year % 100 == a && month == b && day == c || // 年/月/日
month == a && day == b && year % 100 == c || // 月/日/年
day == a && month == b &&year % 100 == c)
printf("%d-%02d-%02d\n",year,month,day);
}
}
}