日期排序计算
Time Limit:1000MS Memory Limit:32768K
Description:
给定一些日期,对它们进行排序并且输出这个日期是该年的第几天。Input:
输入数据有多组,每组由一个N领导,表示接下来有N组日期,每组占一行,若N为0,则输入结束,数据格式为DD/MM/YYYY,依次表示为某日/某月/某年。所有输入日期均合法。Output:
对每一组的数据分两部分输出,所有闰年为第一部分,应该排列在所有非闰年之前,并且以这样的形式(DD\MM\YYYY)输出;若同为闰年或非闰年时,按年,月,日大小排列,即先按年份排列,小的在前;再按月排列,小的在前;最后按日排列,小的在前,并以DD/MM/YYYY的形式输出。两部分数据之间空一行。此外,对每个输出的日期还需要计算出是该年的第几天,接在日期后面空一格输出。每两个组数据之间有两个空行。Sample Input:
5 01/12/2001 25/12/2001 01/01/1999 15/10/1999 10/10/2000 0
Sample Output:
10\10\2000 284 01/01/1999 1 15/10/1999 288 01/12/2001 335 25/12/2001 359 本题是一个典型的日期题目,涉及到日期的计算和排序,关于排序可以使用sort函数。本题主要需要注意的地方在于容易出现Presentation error, 主要会出现在多输出一个回车,解决的办法在于:如果没有闰年,则不需要输出闰年和非闰年的回车。 实例代码:#include<iostream> #include<iomanip> #include<vector> #include<algorithm> #include<map> #include<string> #include<cmath> #include<set> using namespace std; struct Date { int day,month,year,sum; bool isLeap; string name; }; bool cmp(Date a,Date b) { if(a.year > b.year) return true; else if(a.year < b.year) return false; else if(a.month > b.month) return true; else if(a.month < b.month) return false; else if(a.day > b.day) return true; else if(a.day < b.day) return false; } int main() { int leap[13] = {0,31,29,31,30,31,30,31,31,30,31,30,31}; int noLeap[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31}; int n,size = 0; bool isLeap; string s; vector<Date> all; Date tmp; while(cin>>n && n != 0) { if(size != 0) cout<<endl<<endl; size++; all.clear(); isLeap = false; while(n--) { cin>>s; tmp.name = s; tmp.sum = 0; tmp.day = atoi(s.substr(0,s.find_first_of("/")).c_str()); s = s.substr(s.find_first_of("/")+1); tmp.month = atoi(s.substr(0,s.find_first_of("/")).c_str()); s = s.substr(s.find_first_of("/")+1); tmp.year = atoi(s.c_str()); if(tmp.year%400 == 0 ) tmp.isLeap = true; else if(tmp.year%4 == 0) tmp.isLeap = true; else tmp.isLeap = false; if(tmp.isLeap) { for(int i = 1 ; i < tmp.month ; i++) tmp.sum += leap[i]; tmp.sum += tmp.day; } else { for(int i = 1 ; i < tmp.month ; i++) tmp.sum += noLeap[i]; tmp.sum += tmp.day; } all.push_back(tmp); } sort(all.begin(),all.end(),cmp); for(int i = all.size()-1 ; i >=0 ; i--) { if(all[i].isLeap) { all[i].name[2] = '\\'; all[i].name[5] = '\\'; cout<<all[i].name<<" "<<all[i].sum<<endl; isLeap = true; } } //千万要注意的地方,如果没有闰年,如果不判断就会多输出一个回车 if(isLeap) cout<<endl; for(int i = all.size()-1 ; i >=0 ; i--) { if(!all[i].isLeap) cout<<all[i].name<<" "<<all[i].sum<<endl; } } return 0; }