PATB1028:人口普查 【经典】 + 结构体的多级排序 与求最值 其实可以考虑 sort
【知识点】
结构体的多级比较 两次运用,一次是合法验证,一次是求最值比较
三步骤 :
1、结构体;
2、cmp,
3、【合法验证与比较】 (日期left < temp
//重新完成B1028 思路 判断一个数
//思路 : 输入日期 有效(日期min < temp < max) 就cout 然后比较 temp得到最值
//
struct Person{
char name[10];
int yy=1814, mm=12, dd=30;
}temp1,old,young,left1,right1;
//temp 临时比较的person,old实际上是出生日期最小的的人 young是出生日期最大的人哟 别乱了
//left ,right 是边界 合法检测用 MoreEqu(temp,right) 求最值用
MoreEqu(young,temp)
//关键点:多级比较日期 ;;
//需要初始化边间
void init(){
left1.yy = young.yy = 1814;
right1.yy = old.yy = 2014;
left1.mm = right1.mm = young.mm =old.mm= 9;
left1.dd = right1.dd = young.dd = old.dd = 6;
}
bool MoreEqu(Person a, Person b){
if (a.yy!=b.yy)
{
return a.yy >= b.yy;
}
else if (a.mm !=b.mm)
{
return a.mm >= b.mm;
}
else
{
return a.dd >= b.dd;
}
}
bool LessEqu(Person a, Person b){
if (a.yy != b.yy)
{
return a.yy <= b.yy;
}
else if (a.mm != b.mm)
{
return a.mm <= b.mm;
}
else
{
return a.dd <= b.dd;
}
}
void B1028(){
init();
int N;
cin >> N;
int count = 0;
cin.get();
for (int i = 0; i < N; i++)
{
cin >>temp1.name>>temp1.yy>>temp1.mm>>temp1.dd;
if (MoreEqu(temp1, left1) && LessEqu(temp1, right1))
{
count++;
if (LessEqu(young,temp1))
{
young=temp1;
}
if (MoreEqu(old,temp1))
{
old = temp1;
}
}
}
cout << count << " " << old.name << " " << young.name << endl;
}
【参考答案2】
【思路】:
结构体中做标记,flag 如果为true 就count++ ;
sort 之后 ,输出有序数组的最后和最前的人。
//====================================PATB1028 人口普查=====================
//人口普查 person有比较多的属性,所以需要构建struct 另外最最值,所以需要sort
const int maxn = 100000;
struct Person {
bool heli=false;
char name[15];
int yy=1814, mm=12, dd=30;
}temp[maxn];
Person heliPerson[maxn];
bool paixu(Person a,Person b){
if (a.yy!=b.yy){
return a.yy < b.yy;
}
else if (a.mm!=b.mm){
return a.mm < b.mm;
}else{
return a.dd < b.dd;
}
}
//需要写一个函数判断,年龄是否合法
void pandan(Person p){
bool panduan = (p.yy < 2014 && p.yy>1814);
if(panduan){
p.heli = true;
}
else if (p.yy==2014){
if (p.mm<9){
p.heli = true;
}
else if (p.mm==9){
if (p.dd<=6)
{
p.heli = true;
}
}
}
else if (p.yy == 1814){
if (p.mm > 9){
p.heli = true;
}
else if (p.mm == 9){
if (p.dd >= 6)
{
p.heli = true;
}
}
}
}
void rkpcPATB1028(){
int n;
cin>>n;
for (int i = 0; i < n; i++){
cin>>temp[i].name>>temp[i].yy>>temp[i].mm>>temp[i].dd;
}
int count = 0;
for (int i = 0; i < n; i++) {
//=======================================
bool panduan = (temp[i].yy < 2014 && temp[i].yy>1814);
if (panduan){
temp[i].heli = true;
}
else if (temp[i].yy == 2014){
if (temp[i].mm<9){
temp[i].heli = true;
}
else if (temp[i].mm == 9){
if (temp[i].dd <= 6)
{
temp[i].heli = true;
}
}
}
else if (temp[i].yy == 1814){
if (temp[i].mm > 9){
temp[i].heli = true;
}
else if (temp[i].mm == 9){
if (temp[i].dd >= 6)
{
temp[i].heli = true;
}
}
}
//=======================================
if (temp[i].heli){
heliPerson[count++] = temp[i];
}
}
sort(heliPerson, heliPerson + count, paixu);
cout << count <<" "<< heliPerson[count - 1].name <<" "<< heliPerson[0].name<<endl;
}