NOI题目地址(3.1数据结构之结构):http://noi.openjudge.cn/ch0301/
较为复杂的用户自定义数据类型的排序与遍历
6377:生日相同 2.0
解法一:
按照生日日期和名字长短与字母序对班级里所有的同学进行排序,然后遍历输出
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
#include <string.h>
using namespace std;
//自定义数据类型student
struct student
{
string name;
int month;
int day;
};
//比较student类型的数据
bool comp(const student &a,const student &b)
{
if (a.month==b.month&&a.day==b.day)
if (a.name.size()==b.name.size()) return a.name<b.name;
else return a.name.size()<b.name.size();
else if (a.month==b.month) return a.day<b.day;
else return a.month<b.month;
}//比较
int main()
{
int k;
cin>>k;
vector<student> stus;
while(k--)
{
student stu;
cin>>stu.name>>stu.month>>stu.day;
stus.push_back(stu);
}
sort(stus.begin(),stus.end(),comp);
bool flag = false;
bool equelF = false;
string lastN="";
for(vector<student>::iterator it = stus.begin();it!=stus.end();it++)
{
//处理最后一个元素
if(it==stus.end()&&equelF) cout<<(*it).name<<endl;
//处理前n-1个元素
if((*it).month==(*(it+1)).month&&(*it).day==(*(it+1)).day)
{
if(!equelF) cout<<(*it).month<<" "<<(*it).day;
equelF = true;
cout<<" "<<(*it).name;
flag = true;
}else
{
if(equelF) cout<<" "<<(*it).name<<endl;
equelF = false;
}
}
if(!flag)
{
cout<<"None";
}
return 0;
}
解法二:
用二维数组对某天生日人数进行记录,对班级的同学信息按照名字长短与字母序排序,然后遍历输出,这种方法比解法一在比较上的写法更加简洁,但是多耗费了一个13*32的int数组的空间
#include <iostream>
#include <vector>
#include <string.h>
#include <algorithm>
using namespace std;
class student
{
public:
string name;
int m;
int d;
};
int record[13][32]={0};//借助二维数组记录生日相同的同学个数
bool comp(student const &stu1,student const &stu2)
{
if(stu1.name.length()==stu2.name.length())
//or return stu1.name<stu2.name;
return strcmp(stu1.name.c_str(),stu2.name.c_str())<0;
return stu1.name.length()<stu2.name.length();
}
int main()
{
vector<student> vc;
int okFlag = false;
int k;
cin>>k;
for(int i=0;i<k;i++)
{
student stu;
cin>>stu.name>>stu.m>>stu.d;
vc.push_back(stu);
record[stu.m][stu.d]++;
}
sort(vc.begin(),vc.end(),comp);
for(int i=1;i<=12;i++)
{
for(int j=1;j<=31;j++)
{
if(record[i][j]>1)
{
okFlag = true;
cout<<i<<" "<<j;
for(int g=0;g<k;g++)
{
if(vc[g].m==i&&vc[g].d==j)
{
cout<<" "<<vc[g].name;
}
}
cout<<endl;
}
}
}
if(!okFlag)
{
cout<<"None";
}
return 0;
}