您的位置:首页 > 职场人生

PAT 乙级 1028. 人口普查(20)

2017-01-05 18:43 531 查看


1028. 人口普查(20)

某城镇进行人口普查,得到了全体居民的生日。现请你写个程序,找出镇上最年长和最年轻的人。

这里确保每个输入的日期都是合法的,但不一定是合理的——假设已知镇上没有超过200岁的老人,而今天是2014年9月6日,所以超过200岁的生日和未出生的生日都是不合理的,应该被过滤掉。

输入格式:

输入在第一行给出正整数N,取值在(0, 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

分析:

这道题目也不难~步骤主要是:1.获得输入;2.验证这个人的生日是否合法;3.比较最值,这样分解下来就很简单了~

注意如果所有输入都不满足,则应该输出0,后面可能会出现空格,要想办法去除掉~方法看代码吧~

using System;

namespace PAT
{
class Program
{
static Person oldest = new Person();
static Person youngest = new Person();
static void Main(string[] args)
{
int length = int.Parse(Console.ReadLine());
int count = GetPersonCount(length);
string msg = string.Format("{0} {1} {2}", count, oldest.name, youngest.name);
Console.WriteLine(msg.Trim());
}

static int GetPersonCount(int length)
{
int count = 0;
Person temp = new Person();
string[] infos;
string[] birthday;
youngest.year = 0;
oldest.year = 2015;
for (int i = 0; i < length; i++)
{
infos = Console.ReadLine().Split(' ');
birthday = infos[1].Split('/');
temp.name = infos[0];
temp.year = int.Parse(birthday[0]);
temp.month = int.Parse(birthday[1]);
temp.day = int.Parse(birthday[2]);
if (ValidPerson(temp))
{
count++;
if (oldest.CompareTo(temp) < 0)
oldest = temp;
if (youngest.CompareTo(temp) > 0)
youngest = temp;
}
}
return count;
}

//验证这个人的生日是否合法
static bool ValidPerson(Person person)
{
//今天是20140906
Person temp = person;
Person today = new Person();
today.year = 2014;
today.month = 9;
today.day = 6;

if (person.CompareTo(today) < 0)
return false;
temp.year += 200;
if (temp.CompareTo(today) > 0)
return false;
return true;
}

struct Person : IComparable
{
public string name;
public int year;
public int month;
public int day;

public int CompareTo(object person)
{

4000
Person other = (Person)person;
if (year > other.year)
return -1;
else if(year == other.year)
{
if (month > other.month)
return -1;
else if(month == other.month)
{
if (day > other.day)
return -1;
else if (day == other.day)
return 0;
}
}
return 1;
}
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  PAT c# 求职 算法