题目来源:http://noi.openjudge.cn/ch0301/6377/
6377:生日相同 2.0
总时间限制: 1000ms 内存限制: 65536kB
描述
在一个有180人的大班级中,存在两个人生日相同的概率非常大,现给出每个学生的名字,出生月日。试找出所有生日相同的学生。
输入
第一行为整数n,表示有n个学生,n≤ 180。此后每行包含一个字符串和两个整数,分别表示学生的名字(名字第一个字母大写,其余小写,不含空格,且长度小于20)和出生月(1 ≤ m ≤ 12)日(1 ≤ d ≤ 31)。名字、月、日之间用一个空格分隔
输出
每组生日相同的学生,输出一行,其中前两个数字表示月和日,后面跟着所有在当天出生的学生的名字,数字、名字之间都用一个空格分隔。对所有的输出,要求按日期从前到后的顺序输出。对生日相同的名字,按名字从短到长按序输出,长度相同的按字典序输出。如没有生日相同的学生,输出”None”
样例输入
6
Avril 3 2
Candy 4 5
Tim 3 2
Sufia 4 5
Lagrange 4 5
Bill 3 2
样例输出
3 2 Tim Bill Avril
4 5 Candy Sufia Lagrange
-----------------------------------------------------
思路
用两个map,一个map保存同生日的人数,一个map保存同生日的名字的vector
用struct存生日的月和日,重载<运算符
用全局函数cmp重写string的<,用于sort对名字排序
-----------------------------------------------------
代码
#include<fstream> #include<iostream> #include<string> #include<vector> #include<map> #include<algorithm> using namespace std; struct birth { int month, date; bool operator < (const birth &b) const { if (b.month>month) { return true; } else if (b.month==month && b.date>date) { return true; } else { return false; } } bool operator == (const birth &b) const { return (b.month==month && b.date==date); } }; bool cmp (string a, string b) { if (a.size() < b.size()) { return true; } else if (a.size() == b.size()) { if (a<b) { return true; } } return false; } int main() { #ifndef ONLINE_JUDGE ifstream fin ("0301_6277.txt"); int n,i; string name; map< birth, int > num; map< birth, vector<string> > list; fin >> n; for (i=0; i<n; i++) { birth b; fin >> name >> b.month >> b.date; num[b]++; list[b].push_back(name); } fin.close(); map< birth, int >::iterator it1; vector<string> v; vector<string>::iterator it2; bool has = false; for (it1=num.begin(); it1!=num.end(); it1++) { if (it1->second>1) { has = true; cout << it1->first.month << " " << it1->first.date; v = list[it1->first]; sort(v.begin(), v.end(), cmp); for (it2=v.begin(); it2!=v.end(); it2++) { cout << " " << *it2; } cout << endl; } } if (!has) { cout << "None"; } return 0; #endif #ifdef ONLINE_JUDGE int n,i; string name; map< birth, int > num; map< birth, vector<string> > list; cin >> n; for (i=0; i<n; i++) { birth b; cin >> name >> b.month >> b.date; num[b]++; list[b].push_back(name); } map< birth, int >::iterator it1; vector<string> v; vector<string>::iterator it2; bool has = false; for (it1=num.begin(); it1!=num.end(); it1++) { if (it1->second>1) { has = true; cout << it1->first.month << " " << it1->first.date; v = list[it1->first]; sort(v.begin(), v.end(), cmp); for (it2=v.begin(); it2!=v.end(); it2++) { cout << " " << *it2; } cout << endl; } } if (!has) { cout << "None"; } return 0; #endif }