NOI-OJ 3.1 ID: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
struct
sort
关键点
- 自定义排序比较函数
vector
使用sort
sort(v.begin(),v.end(),cmp)
cmp的编写:
bool cmp(string a, string b){
if(a.size()<b.size()){
return 1;
}else if(a.size()>b.size()){
return 0;
}else{
return a < b; // 结果为字典序
}
}
- 思路
- 保证查找速度快,使用map数据结构。
- map的key是日期(month*100+day),确保唯一;value为string,存储学生名字
- 将所有数据读取完成,因为map是按照key来从小到大排列的,所以只要遍历map,然后检查是否大于1个元素,大于的话,则将其中的
vector<string>
按序输出。
知识点
- map遍历方法
map<int,vector<string> > mp;
map<int,vector<string> >::iterator it;
it = mp.begin();
while(it != mp.end()){
// it->first;
// it->second;
it++;
}
- vector遍历方法
vector<string>::iterator t;
for(t=v.begin(); t!=v.end(); t++)
cout << " " << *t;
代码
bool cmp(string a, string b){
if(a.size()<b.size()){
return 1;
}else if(a.size()>b.size()){
return 0;
}else{
return a < b;
}
}
map<int,vector<string> > mp;
map<int,vector<string> >::iterator it;
int main(){
int num;
scanf("%d\n", &num);
for(int i=1;i<=num;i++){
string s;
int month;
int day;
cin >> s >> month >> day;
//scanf("%s %d %d\n", s, &month, &day);
//cout << s << month << day << endl;
it = mp.find(month*100+day);
if(it==mp.end()){
vector<string> v;
v.push_back(s);
mp[month*100+day] = v;
}else{
mp[month*100+day].push_back(s);
}
}
it = mp.begin();
bool but = true;
while(it != mp.end()){ //map应该是排过序的
vector<string> v = it->second;
if((int)v.size()>1){
but=false;
int day = it->first;
cout << day/100 << " " << day%100;
sort(v.begin(), v.end(), cmp);
vector<string>::iterator t;
for(t=v.begin(); t!=v.end(); t++)
cout << " " << *t;
cout << endl;
}
it++;
}
if(but){
cout << "None" << endl;
}
return 0;
}