用vector最后一个用例超时了。。。
Sample Input 1
3 1 000007 James 85 000010 Amy 90 000001 Zoe 60
Sample Output 1
000001 Zoe 60 000007 James 85 000010 Amy 90
Sample Input 2
4 2 000007 James 85 000010 Amy 90 000001 Zoe 60 000002 James 98
Sample Output 2
000010 Amy 90 000002 James 98 000007 James 85 000001 Zoe 60
Sample Input 3
4 3 000007 James 85 000010 Amy 90 000001 Zoe 60 000002 James 90
Sample Output 3
000001 Zoe 60 000007 James 85 000002 James 90 000010 Amy 90
版本一:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student
{
char number[7];
char name[9];
short grade;
};
int cmp_number(const void *p, const void *q)
{
const struct student *p1 = (student*)p;
const struct student *p2 = (student*)q;
return strcmp(p1->number, p2->number);
}
int cmp_name(const void *p, const void *q)
{
const struct student *p1 = (student*)p;
const struct student *p2 = (student*)q;
if(strcmp(p1->name, p2->name) > 0)
{
return 1;
}else if(strcmp(p1->name, p2->name) == 0 && strcmp(p1->number,p2->number) > 0)
{
return 1;
}else
{
return -1;
}
}
int cmp_grade(const void *p, const void *q)
{
const struct student *p1 = (student*)p;
const struct student *p2 = (student*)q;
if(p1->grade > p2->grade)
{
return 1;
}else if(p1->grade == p2->grade && strcmp(p1->number,p2->number) > 0)
{
return 1;
}else
{
return -1;
}
}
student stus[100002];
int main()
{
int n, i, type;
int count = 1;
while(scanf("%d %d", &n, &type) != EOF)
{
if(n == 0)
{
break;
}
for(i = 0; i < n; i ++)
{
scanf("%s %s %hd",stus[i].number, stus[i].name, &stus[i].grade);
}
//快速排序
switch(type)
{
case 1:
qsort(stus, n, sizeof(struct student), cmp_number);
break;
case 2:
qsort(stus, n, sizeof(struct student), cmp_name);
break;
case 3:
qsort(stus, n, sizeof(struct student), cmp_grade);
break;
}
for(i = 0; i < n; i ++)
{
printf("%s %s %hd\n",stus[i].number, stus[i].name, stus[i].grade);
}
}
return 0;
}
版本二:
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct STUDENT
{
string ID;
string Name;
int score;
};
bool greaterID(const STUDENT& s1,const STUDENT& s2)
{
return (s1.ID.compare(s2.ID) > 0)?false:true;
}
bool greaterName(const STUDENT& s1,const STUDENT& s2)
{
int result = s1.Name.compare(s2.Name);
if (result == 0)
{
return (s1.ID.compare(s2.ID) > 0)?false:true;
}
return (result > 0)?false:true;
}
bool greaterScore(const STUDENT& s1,const STUDENT& s2)
{
if (s1.score == s2.score)
{
return (s1.ID.compare(s2.ID) > 0)?false:true;
}
else
{
return (s1.score > s2.score)?false:true;
}
}
int main()
{
int N,type;
cin>>N>>type;
vector<STUDENT> V;
for (int i = 0; i < N; i++)
{
STUDENT stu;
cin>>stu.ID>>stu.Name>>stu.score;
V.push_back(stu);
}
switch(type)
{
case 1:
sort(V.begin(),V.end(),greaterID);
break;
case 2:
sort(V.begin(),V.end(),greaterName);
break;
case 3:
sort(V.begin(),V.end(),greaterScore);
break;
default:
break;
}
for (int i = 0; i < N; i++)
{
cout<<V[i].ID<<" "<<V[i].Name<<" "<<V[i].score<<endl;
}
}