1028 人口普查 (20 分)
题目描述:
某城镇进行人口普查,得到了全体居民的生日。现请你写个程序,找出镇上最年长和最年轻的人。
这里确保每个输入的日期都是合法的,但不一定是合理的——假设已知镇上没有超过 200 岁的老人,而今天是 2014 年 9 月 6 日,所以超过 200 岁的生日和未出生的生日都是不合理的,应该被过滤掉。
输入格式:
输入在第一行给出正整数 N,取值在(0,
1
0
5
10^5
105];随后 N 行,每行给出 1 个人的姓名(由不超过 5 个英文字母组成的字符串)、以及按 yyyy/mm/dd
(即年/月/日)格式给出的生日。题目保证最年长和最年轻的人没有并列。
输出格式:
在一行中顺序输出有效生日的个数、最年长人和最年轻人的姓名,其间以空格分隔。
输入样例:
5
John 2001/05/12
Tom 1814/09/06
Ann 2121/01/30
James 1814/09/05
Steve 1967/11/20
输出样例:
3 Tom John
思路:
这题的坑点有两个一个是注意测试点3会卡你输入全部不合格的时候,这是输出的有效生日个数为0,没有最年长和最年轻的人的姓名,测试点4就是注意代码的效率了,不要用数组存
知识回顾:
字符串大小比较
1.compare 函数的使用
#include <iostream>
using namespace std;
int main(){
string str1="hello";
cout<<str1.compare("helloo")<<endl;//返回-1; str1<str2
cout<<str1.compare("hello")<<endl;//返回0 ; 相等
cout<<str1.compare("hell")<<endl;//返回1; str1>str2
}
2.使用strcmp
#include <iostream>
#include <cstring>
using namespace std;
int main(){
char* str1="hello";
char* str2="hell";
char *str3="helloo";
char *str4="hello";
//原型extern int strcmp(const char *s1,const char *s2);
cout<<strcmp(str1,str2)<<endl;//返回1; str1>str2
cout<<strcmp(str1,str3)<<endl;//返回-1; str1<str2
cout<<strcmp(str1,str4)<<endl;//返回0. 相等
}
原理:
两个字符串自左向右逐个字符相比(按ASCII值大小相比较),直到出现不同的字符或遇’\0’为止。
当两个数的位数一样,则直接可以应用字符串的比较。
string可以直接比较大小
AC代码
#include<bits/stdc++.h>
#define _CRT_SECURE_NO_WARNINGS
using namespace std;
const int N = 1e5 + 6;
const int maxn = 0x3f3f3f3f;
typedef long long ll;
int main() {
int n;
cin >> n;
int cnt = 0;
string name;
string maxb = "1814/09/06", minb = "2014/09/06", birth, maxn, minn;
for (int i = 0; i < n; i++) {
cin >> name >> birth;
if (birth >= "1814/09/06" && birth <= "2014/09/06") {
cnt++;
if (birth >= maxb) {
maxb = birth;
minn = name;
}
if (birth <= minb) {
minb = birth;
maxn = name;
}
}
}
cout << cnt;
if (cnt != 0) {
cout << " " <<maxn << " " << minn;
}
return 0;
}