1028 人口普查 (20 分)

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;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值