//题目考察结构体排序,刚开始有一个case超时,
(1)将输入改为scanf
(2)修改将string
改为char,C++的string是相对char字符串更加耗时
(3)然后对于ID比较,先前是用字符串比较函数strcmp比较耗时,修改为整型比较,就很快,最后补齐0即可
//1028 #include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string> #include <vector> #include <algorithm> using namespace std; typedef struct Node { int ID; char Name[20]; int grade; }; int C; bool cmp(Node n1,Node n2) { if(C==1) return n1.ID < n2.ID; else if(C == 2) { if(strcmp(n1.Name,n2.Name)==0) return n1.ID < n2.ID ; return strcmp(n1.Name,n2.Name)<0; } else { if(n1.grade == n2.grade) return n1.ID < n2.ID; return n1.grade <n2.grade; } } int main() { int i; int N; while(scanf("%d %d",&N,&C)!=EOF) { vector <Node> nlist(N); for(i = 0 ;i < N;i++) { scanf("%d %s %d",&nlist[i].ID,nlist[i].Name,&nlist[i].grade); } sort(nlist.begin(),nlist.end(),cmp); for(i =0;i< N;i++) { printf("%06d %s %d\n",nlist[i].ID,nlist[i].Name,nlist[i].grade); } } return 0; }