题目
某城镇进行人口普查,得到了全体居民的生日。现请你写个程序,找出镇上最年长和最年轻的人。
这里确保每个输入的日期都是合法的,但不一定是合理的——假设已知镇上没有超过 200 岁的老人,而今天是 2014 年 9 月 6 日,所以超过 200 岁的生日和未出生的生日都是不合理的,应该被过滤掉。
输入格式:
输入在第一行给出正整数 N,取值在(0,10 ^ 5];随后 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
思路
通过比较字符串判断日期大小,只记录当前最大和最小者的名字和生日。
由于输入量较大,为了提高读入效率用scanf读入char*类型字符串,比较和复制操作需使用:
int strcmp ( const char * str1, const char * str2 );
char * strcpy ( char * destination, const char * source );
偶然发现一片新大陆,能解决cin效率远慢于scanf的问题,只需在main函数第一行加上:
std::ios::sync_with_stdio(false);
作用是取消iostream与stdio的默认关联同步,取消同步后的iostream的性能倍增。只要注意不要再混用iosteam和stdio即可。
这样就能愉快地使用cin读string类型了。
算法
下面分别是用scanf和cin两个版本的代码。
C风格字符串比较、复制:
#include <stdio.h>
#include <string.h>
int main()
{
int n;
scanf("%d", &n);
char name[6];
char date[11];
int count = 0;
char oldName[6];
char youngName[6];
char oldLimit[] = "1814/09/06";
char youngLimit[] = "2014/09/06";
char young[] = "0000/00/00";
char old[] = "2100/00/00";
for (int i=0; i<n; i++){
scanf("%s %s", name, date);
if (strcmp(date, oldLimit) >= 0 && strcmp(youngLimit, date) >= 0){
if (strcmp(date, young)>0){
strcpy(young, date);
strcpy(youngName, name);
}
if (strcmp(old, date)>0){
strcpy(old, date);
strcpy(oldName, name);
}
count++;
}
}
if (count==0){
printf("0\n");
}
else {
printf("%d %s %s\n", count, oldName, youngName);
}
return 0;
}
C++风格字符串比较、复制:
#include <iostream>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
int n;
cin >> n;
string name;
string date;
string oldName;
string youngName;
string oldLimit = "1814/09/06";
string youngLimit = "2014/09/06";
string young = "0000/00/00";
string old = "2100/00/00";
int count = 0;
for (int i=0; i<n; i++){
cin >> name >> date;
if (date >= oldLimit && date <= youngLimit){
if (date > young){
young = date;
youngName = name;
}
if (date < old){
old = date;
oldName = name;
}
count++;
}
}
if (count==0){
printf("0\n");
}
else {
cout << count << " " << oldName << " " << youngName << endl;
}
return 0;
}
2223

被折叠的 条评论
为什么被折叠?



