PAT 1028 人口普查 (20 分)

#include <iostream>
#include<algorithm>//
#include<cstdio>
using namespace std;
struct person{
  char name[10];
  int year,month,day;
}old,young,l,r,temp;//l 左端 r 右端 

bool cmp(person a,person b){//从小到大排列 
  if(a.year!=b.year) return a.year<=b.year;
  else if(a.month!=b.month) return a.month<=b.month;
  else return a.day<=b.day;
}

void inti(){//初始化 
  l.year=young.year=1814;
  r.year=old.year=2014;
  l.month=r.month=young.month=old.month=9;
  l.day=r.day=young.day=old.day=6;
}
int main() {
  inti();
  int n,num=0;
  cin>>n;
  for(int i=0;i<n;i++){
    cin>>temp.name;
    scanf("%d/%d/%d",&temp.year, &temp.month, &temp.day);
    if(cmp(l,temp)&&cmp(temp,r)){
      num++;
      if(cmp(temp,old)) old=temp;
      if(cmp(young,temp)) young=temp;
    }
    
  } 
  if(num==0) cout<<0<<endl;
    else cout<<num<<' '<<old.name<<' '<<young.name<<endl;
    return 0;
}

//方法2
#include <iostream>
#include<set>
using namespace std;
struct people {
    char name[7];
    int y, m, d;
    bool operator <(const people &a)const {   //定义结构体的比较方式 重载
        if (a.y == y) 
            if (a.m == m)
                return a.d >= d;
            else
                return a.m > m;
        else
            return a.y > y;//数字小的有限,即年长优先
    }
};
int main() {
    set < people> myset;
    people temp;
    int n;
    cin >> n;
    while (n--) {
        scanf("%s %d/%d/%d", temp.name, &temp.y, &temp.m, &temp.d);
        if (temp < people{ "",2014,9,6 }&&people{ "",1814,9,6 } < temp)    //判断是否合理
            myset.insert(temp);   //放进set容器中
    }
    cout << myset.size();//有效生日数
    if (myset.size())      //注意当size=0时不能访问begin
        cout << " " << myset.begin()->name << " " << myset.rbegin()->name;
    return 0;
}

GitHub

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容