【PAT乙级1028】——人口普查

思路:
规定了最大年龄为200岁,根据今天是2014/9/6,所以最早出生的日期为1814/9/6,只有在这两个时间之间的才是合法的,统计这个的变量自加;
每输入一个姓名 年/月/日就和当前的最值年月日比较,这里注意以下逻辑,合理日期内,越接近 2014/9/6年龄越小,否则年龄越大;换句话说,年月日越大,年龄越小;

看了解析后,解析思路就是在判断年龄大小时,直接用字符串判断了,清晰明了;

解析代码如下,提交使用c++

#include 
using namespace std;

int main() {
	int n, cnt = 0;
	cin >> n;
	string name, birth, maxname, minname, maxbirth = "1814/09/06",minbirth = "2014/09/06";
	for (int i = 0; i < n; i++) {
		cin >> name >> birth;
		if (birth >= "1814/09/06" && birth <= "2014/09/06") {
			cnt++;
			if (birth >= maxbirth) {
				maxbirth = birth;
				maxname = name;
			}
			if (birth <= minbirth) {
				minbirth = birth;
				minname = name;
			}
		}
	}
	cout << cnt;
	if (cnt != 0) cout << " " << minname << " " << maxname;
	return 0;
}

自己是将时间用数值接收的,比较起来有点复杂,代码已AC,提交使用g++

#include
using namespace std;

int main()
{
	int n, count = 0; 
	int tmpyear, tmpmon, tmpday;
	int maxyear, maxmon, maxday;
	int minyear, minmon, minday;
	string maxname, minname, tmpname; 
	scanf("%d", &n);
	
	while(n--)
	{
		cin >> tmpname;
		scanf("%d/%d/%d", &tmpyear, &tmpmon, &tmpday);
		if(((tmpyear<2014)||(tmpyear==2014&&tmpmon<9)||(tmpyear==2014&&tmpmon==9&&tmpday<=6))
		&&((tmpyear>1814)||(tmpyear==1814&&tmpmon>9)||(tmpyear==1814&&tmpmon==9&&tmpday>=6)))
		//判断是否是合理时间
		{
			count++;
			if(count==1)	//最值赋初值
			{
				maxname = tmpname; maxyear = tmpyear; maxmon = tmpmon; maxday = tmpday;
				minname = tmpname; minyear = tmpyear; minmon = tmpmon; minday = tmpday;
			}
			else		//与最值比较,看是否更新最值
			{
				if(tmpyear<maxyear||(tmpyear==maxyear&&tmpmon<maxmon)
				||(tmpyear==maxyear&&tmpmon==maxmon&&tmpday<maxday))
				{
					maxname = tmpname; maxyear = tmpyear; maxmon = tmpmon; maxday = tmpday;
				}
				if(tmpyear>minyear||(tmpyear==minyear&&tmpmon>minmon)
				||(tmpyear==minyear&&tmpmon==minmon&&tmpday>minday))
				{
					minname = tmpname; minyear = tmpyear; minmon = tmpmon; minday = tmpday;
				}
			}
		}
	}
	if(count)
	{
		cout << count << " " << maxname << " " << minname <<endl;
	}
	else
	{
		cout << count << endl; 
	}
	
		
	return 0;
}  

你可能感兴趣的:(PAT乙级)