浙大PAT 1028题 1028. List Sorting

此题用了Qsort模板,200ms时限,用C++输入输出时超时,改用C,90ms过了

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
typedef struct{
	char id[10];
	char name[10];
	int score;
}Student;
Student stu[100005];
int n,c;
int cmp(const void *atmp,const void *btmp){//参数必须先写出const void *
	Student *a=(Student *)atmp;
	Student *b=(Student *)btmp;
	if(c==1){
		return strcmp(a->id,b->id);
	}
	else if(c==2){
		if(strcmp(a->name,b->name)==0) return strcmp(a->id,b->id);
		else return strcmp(a->name,b->name);
	}
	else if(c==3){
		if(a->score==b->score) return strcmp(a->id,b->id);
		else return a->score-b->score;
	}
	return 0;
}

int main(){
	int i,j;
	scanf("%d %d",&n,&c);
	for(i=0;i<n;i++)
		scanf("%s %s %d",stu[i].id,stu[i].name,&stu[i].score);
	qsort(stu,n,sizeof(Student),cmp); 
    //qsort(数组首地址,元素个数,元素大小,自定义排序函数)
	for(i=0;i<n;i++)
		printf("%s %s %d\n",stu[i].id,stu[i].name,stu[i].score);
	return 0;
}



 

你可能感兴趣的:(浙大PAT 1028题 1028. List Sorting)