List Sorting(PAT)

1.题目描述

Excel can sort records according to any column. Now you are supposed to imitate this function.
Excel可以根据任何列对记录进行排序。现在你应该模仿这个函数。

2.输入描述:

Each input file contains one test case. For each case, the first line contains two integers N (<=100000) and C, where N is the number of records and C is the column that you are supposed to sort the records with. Then N lines follow, each contains a record of a student. A student’s record consists of his or her distinct ID (a 6-digit number), name (a string with no more than 8 characters without space), and grade (an integer between 0 and 100, inclusive).
每个输入文件包含一个测试用例。对于每一种情况,第一行包含两个整数N(<=100000)和C,其中N是记录的数目,C是要对记录进行排序的列。接下来是N行,每一行都包含一个学生的记录。学生的记录包括他或她独特的ID(一个6位数字),姓名(一个没有空格的字符串,不超过8个字符)和成绩(一个0到100之间的整数,包括在内)。

3.输出描述:

For each test case, output the sorting result in N lines. That is, if C = 1 then the records must be sorted in increasing order according to ID’s; if C = 2 then the records must be sorted in non-decreasing order according to names; and if C = 3 then the records must be sorted in non-decreasing order according to grades. If there are several students who have the same name or grade, they must be sorted according to their ID’s in increasing order.
对于每个测试用例,以N行输出排序结果。也就是说,如果C=1,则记录必须按照ID‘s按递增顺序排序;如果C=2时,则必须按名称按非递减顺序排序;如果C=3,则记录必须按等级按非递减顺序排序。如果有几个同名或同级的学生,他们必须按照他们的ID按增加的顺序排序。

4.输入例子:

3 1
000007 James 85
000010 Amy 90
000001 Zoe 60

5.输出例子:

000001 Zoe 60
000007 James 85
000010 Amy 90

6.源代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct
{
	int id;
	char name[9];
	int grade;
}student;

int cmp1(const void *a, const void *b)//ID排序
{
	student *s1=(student*)a;
	student *s2=(student*)b;
    return s1->id - s2->id;
}
int cmp2(const void *a, const void *b)//姓名二级排序
{
	student *s1=(student*)a;
	student *s2=(student*)b;
	if(strcmp(s1->name,s2->name)!=0)
		return strcmp(s1->name,s2->name);
	else
		return s1->id - s2->id;
	
}
int cmp3(const void *a, const void *b)//成绩二级排序
{
	student *s1 = (student *)a;
	student *s2 = (student *)b;
    if(s1->grade != s2->grade)
		return s1->grade - s2->grade;
	else
		return s1->id - s2->id;
}


int main()
{
	int i,N,C;
	scanf("%d %d",&N,&C);
	
	student *stu;
	stu=(student*)malloc(N*sizeof(student));

	for(i=0;i<N;i++)
		scanf("%d %s %d",&stu[i].id,stu[i].name,&stu[i].grade);

	if(C==1)	
		qsort(stu,N,sizeof(student),cmp1);
	else if(C==2)
		qsort(stu,N,sizeof(student),cmp2);
	else
		qsort(stu,N,sizeof(student),cmp3);

	for(i=0;i<N;i++)
		printf("%06d %s %d\n",stu[i].id,stu[i].name,stu[i].grade);
	return 0;
}
全部评论

相关推荐

OPSL:钱确实给的多,但是追责这一点比较迷惑…3个月具体如何计算呢?出勤天数30*3吗?还是21*3呢?万一中间学校有安排怎么办呢?这个得多问一问呀
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务